MSSQL Exploitation: OPENROWSET, xp_cmdshell, and Database Attack Primitives
A penetration tester's complete reference to MSSQL attack surface — from SQL injection to OS shell, data exfiltration to domain compromise.
Microsoft SQL Server remains one of the most common database platforms in enterprise environments, and it is consistently one of the most rewarding targets in internal penetration tests. MSSQL offers a rich set of built-in functionality that, when misconfigured or when accessed through SQL injection, gives an attacker capabilities ranging from data exfiltration to full operating system command execution to Active Directory domain compromise.
This post covers the core attack primitives every pentester needs to know: OPENROWSET for data exfiltration and file access, xp_cmdshell for OS command execution, hash capture techniques, privilege escalation within SQL Server, and the relationship between MSSQL and Active Directory that makes database compromise a frequent path to domain admin.
Who this is for: Penetration testers, OSCP/OSCP+ candidates, and security engineers who encounter MSSQL during internal engagements. Assumes familiarity with SQL injection fundamentals and basic Windows/AD concepts. All techniques demonstrated here require authorized access — this is pentest documentation, not a hacking tutorial.
Initial Access
Getting Into MSSQL
Before exploiting MSSQL internals, you need access. The most common paths in during a penetration test:
| Access Vector | Details |
|---|---|
| SQL Injection | Web application or API vulnerability that passes attacker-controlled input to MSSQL queries. The classic path. Stacked queries (; statement separator) are supported in MSSQL, which massively expands what you can do compared to databases that only allow single statements. |
| Default / Weak Credentials | SA account with blank or weak password, application service accounts with predictable credentials. Spray with CrackMapExec: crackmapexec mssql target -u sa -p passwords.txt |
| Credential Reuse | Credentials captured elsewhere (Responder, LSASS dump, config files) that work against MSSQL. Try captured domain creds with Windows authentication. |
| Connection String Leaks | Hardcoded credentials in web.config, appsettings.json, environment variables, source code repositories, or SharePoint/wiki pages. |
| SPN Discovery | MSSQL instances register SPNs in Active Directory. Enumerate with GetUserSPNs.py or PowerUpSQL's Get-SQLInstanceDomain — gives you instance locations and potential Kerberoasting targets. |
Discovery and Enumeration
First Steps After Access
Once connected, enumerate your privileges and the environment before doing anything aggressive:
Data Exfiltration
OPENROWSET — Remote Data Access and Exfiltration
OPENROWSET is a T-SQL function that performs a one-time, ad-hoc connection to a remote OLE DB data source — another SQL Server, an Access database, an Excel file, or any OLE DB-compatible source. It appears in SELECT, INSERT, UPDATE, and DELETE statements without requiring a persistent linked server configuration. It also supports a BULK provider for reading local files directly.
From a pentester's perspective, OPENROWSET gives you three capabilities: outbound data exfiltration to an attacker-controlled database, local file reading on the database server, and NTLM hash capture via UNC path authentication.
Prerequisites
- The
Ad Hoc Distributed Queriesserver option must be enabled (disabled by default since SQL Server 2005 — but always check, because DBAs re-enable it for legitimate reasons) - The executing user needs appropriate permissions — sysadmin can do everything; non-sysadmin users need explicit
ADMINISTER BULK OPERATIONSfor BULK operations - For outbound exfiltration: TCP connectivity from the database server to your listener (default port 1433, but you can specify any port)
OPENROWSET Syntax
The key arguments:
| Argument | What It Does |
|---|---|
provider_name | OLE DB provider. For MSSQL-to-MSSQL: 'SQLOLEDB' (legacy) or 'MSOLEDBSQL' (modern). For ODBC: 'MSDASQL'. |
datasource | Server address. Use Network=DBMSSOCN; prefix for TCP/IP. Append ,port after IP for non-standard ports. |
user_id / password | Credentials for the remote data source — these are credentials on your attacker-controlled server, not the target. |
provider_string | Alternative: entire connection string in one parameter. |
'query' | Pass-through query executed on the remote server. Results returned to the local context. |
BULK 'file_path' | Read a local file. SINGLE_CLOB = text, SINGLE_BLOB = binary, SINGLE_NCLOB = Unicode text. |
Technique 1: Outbound Data Exfiltration
The core attack: use OPENROWSET to push query results from the target database to a SQL Server you control. The target database initiates the outbound TCP connection — if egress filtering blocks port 1433, specify a different port.
Attacker Setup
Exfiltration Queries (executed on target)
Column matching is critical: The INSERT INTO OPENROWSET ... SELECT pattern requires that the columns returned by your local SELECT match the columns of the remote table in number and compatible data types. If they do not match, the query fails silently or throws a type mismatch error. Use NVARCHAR(MAX) on your loot table for maximum flexibility, and cast columns as needed.
Technique 2: Local File Read (BULK Provider)
The BULK provider reads files on the database server's filesystem — anything the SQL Server service account can access. This is how you extract configuration files, connection strings, and potentially credential material without needing OS command execution.
Technique 3: NTLM Hash Capture via UNC Path
This is one of the most reliable and impactful techniques. When MSSQL accesses a UNC path (\\server\share), the SQL Server service account authenticates to the remote SMB server — sending its NTLMv2 hash. You do not need OPENROWSET enabled for this; several built-in procedures trigger UNC authentication.
Attacker-Side Capture
Why this matters: SQL Server service accounts are frequently domain accounts with elevated privileges — sometimes local admin on multiple servers, sometimes members of high-privilege AD groups. Capturing and cracking (or relaying) the service account hash can give you lateral movement across the entire environment. The xp_dirtree method is especially valuable because it does not require sysadmin or any special configuration — any authenticated database user can trigger it.
OS Access
xp_cmdshell — Operating System Command Execution
xp_cmdshell is the most direct path from SQL Server access to operating system compromise. It spawns a Windows command shell process, executes the specified command, and returns output as rows of text. This has been disabled by default since SQL Server 2005, but if you have sysadmin privileges, you can re-enable it with two configuration commands.
Enable and Execute
Getting a Reverse Shell
Detection warning: Enabling xp_cmdshell generates SQL Server Audit events (specifically, sp_configure changes are logged). Most EDR solutions hook cmd.exe and powershell.exe child processes spawned by sqlservr.exe — this is a high-fidelity detection. In mature environments, expect this to trigger alerts within seconds. Consider stealthier alternatives (below) for environments with active monitoring.
Disable After Use
Alternatives
Beyond xp_cmdshell: Stealthier Execution Methods
When xp_cmdshell is too noisy or too monitored, MSSQL provides several alternative code execution paths. Each has different prerequisites, detection profiles, and capabilities.
sp_OACreate — OLE Automation
Instantiate COM objects within SQL Server. The classic technique uses wscript.shell to execute OS commands without touching xp_cmdshell.
CLR Assembly — Custom .NET Code Execution
Load a custom .NET assembly into SQL Server for arbitrary code execution. This is the most powerful technique — you can run anything .NET can do, including fully functional reverse shells, in-memory tooling, and C# implants.
Tool: DAFT (Database Audit Framework & Toolkit) and PowerUpSQL by NetSPI include pre-built CLR assemblies for command execution that handle the hex encoding and deployment automatically.
SQL Server Agent Jobs
Create a scheduled SQL Agent job that executes an OS command. Stealthier than xp_cmdshell because the command runs under the SQL Agent service account context, and the execution is decoupled from your session.
Linked Server Hopping — Lateral Movement
Linked servers create persistent connections between SQL Server instances. If the target has linked servers configured (common in enterprise environments), you can execute queries — and potentially OS commands — on remote instances through the link chain.
Linked server abuse is lateral movement. In large enterprises, you can chain through 3-4 linked servers and end up on a database server in a different network segment, datacenter, or even a different domain trust — all authenticated transparently. Map linked server topology early and treat each hop as a new compromise opportunity.
Comparison: Execution Methods
| Method | Requirement | Detection Profile | Output Capture |
|---|---|---|---|
xp_cmdshell |
sysadmin | High — well-monitored, sp_configure change logged | Direct (returns rows) |
sp_OACreate |
sysadmin | Medium — less commonly monitored than xp_cmdshell | Indirect (write to file, read back) |
| CLR Assembly | sysadmin | Medium-Low — assembly registration logged but execution blends in | Direct (custom implementation) |
| SQL Agent Job | sysadmin or Agent role | Low — Agent jobs are normal; decoupled execution | Indirect (write to file) |
| Linked Servers | Varies per link config | Low-Medium — cross-server queries are normal traffic | Direct (via OPENQUERY) |
xp_dirtree (hash capture) |
Any authenticated user | Low — no configuration change needed | N/A (captures auth, not output) |
Privilege Escalation
Escalating Within SQL Server
If you land on MSSQL as a low-privilege user and need sysadmin, there are several escalation paths:
Impersonation (EXECUTE AS)
Trustworthy Database Escalation
Service Account Abuse
AD Integration
MSSQL and Active Directory
MSSQL is deeply integrated with Active Directory in most enterprise environments. This integration creates attack paths that flow bidirectionally — from AD to MSSQL and from MSSQL to AD.
Discovery via AD
From MSSQL to Domain Compromise
Common finding: SQL Server service accounts running as domain admin, or with unconstrained delegation enabled, or with write access to Group Policy Objects. Any of these turns MSSQL compromise into immediate domain compromise. Always check the service account's AD group memberships and permissions with BloodHound after capturing or cracking the credentials.
Beyond MSSQL
Other Database Targets — Quick Reference
MSSQL is not the only database you will encounter in the field. Each platform has its own exploitation primitives:
| Database | Key Attack Vectors | Tools |
|---|---|---|
| PostgreSQL | COPY TO/FROM PROGRAM (direct OS command execution if superuser), pg_read_file() and pg_read_binary_file() for local file read, large object abuse (lo_import/lo_export) for file write, extension loading for arbitrary code execution |
psql, SQLMap, Metasploit |
| MySQL / MariaDB | LOAD DATA LOCAL INFILE (read client-side files via rogue MySQL server), SELECT ... INTO OUTFILE (write files — e.g., webshell to webroot), User Defined Functions (UDF) compiled shared library loading for OS command execution |
mysql client, SQLMap, Metasploit, Rogue MySQL Server |
| Oracle | Java stored procedures for OS access, DBMS_SCHEDULER for command execution, UTL_HTTP / UTL_TCP for outbound connections, TNS listener attacks, default credentials (SYS/CHANGE_ON_INSTALL, DBSNMP/DBSNMP) |
odat (Oracle Database Attacking Tool), SQLMap, Metasploit, tnscmd10g |
| MongoDB | NoSQL injection ($gt, $ne, $regex operators), unauthenticated access (common on legacy versions), $where JavaScript injection for server-side code execution, SSRF via $lookup |
mongosh, NoSQLMap, Nuclei templates |
| Redis | Unauthenticated access (default configuration), CONFIG SET dir/dbfilename to write SSH authorized_keys or crontabs, module loading (MODULE LOAD) for native code execution, Lua scripting via EVAL |
redis-cli, redis-rogue-server, Metasploit |
Reference
MSSQL Exploitation Toolkit
| Tool | Purpose |
|---|---|
Impacket mssqlclient.py | Interactive MSSQL client — supports Windows and SQL auth, hash authentication, xp_cmdshell enable/exec, file upload/download. The go-to for manual MSSQL interaction from Linux. |
CrackMapExec / NetExec | MSSQL credential spraying, command execution, enumeration: crackmapexec mssql target -u user -p pass -x 'whoami' |
PowerUpSQL | PowerShell toolkit for MSSQL discovery, enumeration, and exploitation in AD environments. Finds instances via SPN enumeration, audits misconfigs, tests linked servers, deploys CLR assemblies. |
SQLMap | Automated SQL injection — --os-shell (interactive OS shell), --os-pwn (Meterpreter), --file-read, --file-write. Handles MSSQL stacked queries natively. |
Metasploit | auxiliary/scanner/mssql/mssql_login (credential testing), exploit/windows/mssql/mssql_payload (shell delivery), auxiliary/admin/mssql/mssql_exec (command execution), auxiliary/admin/mssql/mssql_escalate_dbowner |
HeidiSQL / Azure Data Studio | GUI clients for interactive database exploration and manual query execution when you have credentials. |
Responder | Captures NTLMv2 hashes when MSSQL authenticates to your UNC path. Essential companion to xp_dirtree / OPENROWSET UNC techniques. |
ntlmrelayx (Impacket) | Relay captured MSSQL service account authentication to other services instead of cracking — direct lateral movement. |
Originally published circa 2012 as an OPENROWSET reference. Fully rewritten and expanded — March 2026.
For the complete penetration testing framework this belongs to, see the companion post: The Essential Penetration Testing Framework — 2026 Edition.