An xp_cmdshell proxy supplies a secondary security context that lets non-sysadmin users execute xp_cmdshell when they have the required EXEC permission. That convenience can create an opaque route from database permissions to operating-system access. section 14.4
Treat these as warning signs:
- Do not assume sysadmin membership is the only route to xp_cmdshell; CONTROL SERVER, direct EXEC permission through a proxy, or IMPERSONATE permission can also qualify a caller. section 14.4
- Question the operational justification: using xp_cmdshell where operating-system access is restricted can become a policy-breaking back door and enable lateral movement. section 14.4
Listing 14.5 Creating a trigger to prevent xp_cmdshell execution
EXEC sp_addmessage 50001, 16, 'Attempt to disable xp_cmdshell' ;
GO
CREATE TRIGGER prevent_xp_cmdshell
ON ALL SERVER
FOR ALTER_INSTANCE
AS
BEGIN
DECLARE @Statement NVARCHAR(4000) ;
SET @Statement = (SELECT EVENTDATA().value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]',
'nvarchar(4000)')) ;
IF (CHARINDEX('sp_configure', @Statement) > 0)
AND (CHARINDEX('xp_cmdshell', @Statement) > 0)
BEGIN
RAISERROR(50001, 16, 1, 'Attempt to disable xp_cmdshell') WITH LOG ;
ROLLBACK ;
END
END ;
GO
A server-level trigger can log and roll back attempts to change xp_cmdshell configuration, providing a concrete defensive control. section 14.4
