MSSQL exploitation often changes server configuration or creates artifacts. Cleanup is part of the lab.
Cleanup Commands
Delete SQL Agent job:
EXEC msdb.dbo.sp_delete_job @job_name='poc_job';
EXEC msdb.dbo.sp_delete_job @job_name='Malicious Job';
Drop CLR procedure and assembly:
DROP PROCEDURE IF EXISTS dbo.sp_cmd;
DROP ASSEMBLY IF EXISTS myexec;
Drop TRUSTWORTHY escalation procedure:
DROP PROCEDURE IF EXISTS dbo.make_sysadmin;
Revert impersonation:
REVERT;
Disable features if the lab enabled them:
EXEC sp_configure 'xp_cmdshell', 0;
RECONFIGURE;
EXEC sp_configure 'Ole Automation Procedures', 0;
RECONFIGURE;
EXEC sp_configure 'Ad Hoc Distributed Queries', 0;
RECONFIGURE;
EXEC sp_configure 'clr enabled', 0;
RECONFIGURE;
EXEC sp_configure 'external scripts enabled', 0;
RECONFIGURE;
Remove OS artifacts through shell/admin access:
C:\agent.txt
C:\ole.txt
C:\pwned.txt
C:\tmp\rev.exe
C:\Windows\Temp\p.exe
C:\CLRExec.dll
downloaded payloads
written webshells
Detection
Watch for:
sp_configureenabling dangerous featuresxp_cmdshellsp_OACreate,sp_OAMethod,WScript.Shell,Scripting.FileSystemObject- SQL Agent jobs with CmdExec or PowerShell steps
CREATE ASSEMBLYwithUNSAFEsp_execute_external_scriptOPENROWSET(BULK...)xp_regread,xp_regenumkeysxp_dirtree,xp_subdirs,xp_fileexistto UNC pathsEXECUTE AS LOGINALTER SERVER ROLE sysadmin ADD MEMBERsp_addsrvrolemember- linked server
EXECUTE AT - suspicious outbound SMB from SQL Server hosts
Useful queries:
SELECT name, value_in_use
FROM sys.configurations
WHERE name IN ('xp_cmdshell','Ole Automation Procedures','Ad Hoc Distributed Queries','clr enabled','external scripts enabled');
Find Agent job commands:
SELECT j.name, s.step_id, s.subsystem, s.command
FROM msdb.dbo.sysjobs j
JOIN msdb.dbo.sysjobsteps s ON j.job_id=s.job_id;
Find assemblies:
SELECT name, permission_set_desc, create_date
FROM sys.assemblies;
Find linked servers:
SELECT name, data_source, is_rpc_out_enabled
FROM sys.servers
WHERE is_linked = 1;
Remediation
- Do not grant
sysadminbroadly. - Remove unnecessary SQL Agent roles.
- Disable
xp_cmdshell, OLE Automation, external scripts, CLR unsafe assemblies, and Ad Hoc Distributed Queries unless required. - Restrict linked server mappings and disable RPC OUT where not required.
- Avoid SQL service accounts with broad domain privileges.
- Use managed service accounts or gMSA where appropriate.
- Prevent SQL service accounts from local admin rights unless required.
- Monitor outbound SMB from SQL servers.
- Block unnecessary SMB egress.
- Remove unnecessary
IMPERSONATEgrants. - Avoid TRUSTWORTHY databases; use certificate signing where server-level permissions are needed.
- Audit SQL Agent jobs, proxies, and credentials.
- Patch SQL Server and client tooling.
- Separate database admin roles from Windows/domain admin roles.