MS SQL Command Execution

The xp_cmdshell procedure can be used to execute shell commands on the SQL server if you have sysadmin privileges. Invoke-SQLOSCmd from PowerUpSQL provides a simple means of using it.

beacon> powershell Invoke-SQLOSCmd -Instance "sql-2.dev.cyberbotic.io,1433" -Command "whoami" -RawResults

dev\mssql_svc

\

The same will fail if you try manually in Heidi or mssqlclient, because xp_cmdshell is disabled.

SQL> EXEC xp_cmdshell 'whoami';
[-] ERROR(SQL-2): Line 1: SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the security configuration for this server.

\

To enumerate the current state of xp_cmdshell, use:

SELECT value FROM sys.configurations WHERE name = 'xp_cmdshell';

\

\

A value of 0 shows that xp_cmdshell is disabled. To enable it:

\

Query sys.configurations again and the xp_cmdshell value should be 1; and xp_cmdshell will also now work.

\

OPSEC If you're going to make this type of configuration change to a target, you must ensure you set it back to its original value afterwards. The reason this works with Invoke-SQLOSCmd is because it will automatically attempt to enable xp_cmdshell if it's not already, execute the given command, and then disable it again. This is a good example of why you should study your tools before you use them, so you know what is happening under the hood.

With command execution, we can work towards executing a Beacon payload. As with other servers in the lab, the SQL servers cannot talk directly to our team server in order to download a hosted payload. Instead, we must setup a reverse port forward to tunnel that traffic through our C2 chain.

\

Next, host smb_x64.ps1 at /b on the team server. We know SMB will work because we can validate that port 445 is open on the target SQL server.

\

We can now download and execute the payload.

\

Keep an eye on your web log so you know when the payload has been fetched.

\

You can then link to the Beacon.

\

\

What payload would you use if port 445 was closed? Experiment with using the pivot listener here instead of SMB.

Last updated