If you ever needed to debug a permission related issue when using xp_cmdshell, you have probably realized that a crucial piece of information is about what particular account xp_cmdshell is executing under. If you are the administrator of the database, you already know the context used by xp_cmdshell, but otherwise you may not have that information. Here are some tips on how to find more.
First, if you have a command line tool that displays the current context, like whoami or a utility for dumping the security contex, you can just execute that under xp_cmdshell. That’s pretty easy. But what if there is no such tool available? One thing you can try in this case is to loop back into SQL (assuming the xp_cmdshell account has access to the database – it usually does) and just ask SQL for more information with queries like the following:
EXECxp_cmdshell ‘osql -E -Q”select suser_sname()”‘
EXECxp_cmdshell ‘osql -E -Q”select * from sys.login_token”‘
Don’t forget to pass in the server/instance name using the -S option, if you are not dealing with a default instance. These should give you plenty of information about the xp_cmdshell context and should help you figure out any access permission issue.
Given that I am on the topic of xp_cmdshell, here’s how the command can be enabled using T-SQL:
sp_configure‘show advanced options’, 1
sp_configure ‘xp_cmdshell’, 1