数据库权限检查

本篇文章仅用于检查主体所拥有的权限。我们可以按照 实例->数据库->数据库对象 逐一检查。

--实例级别
select * from sys.server_principals --服务器主体
select * from sys.server_role_members --服务器角色成员
select * from sys.server_permissions --权限分配
--数据库级别
select * from sys.database_principals --数据库主体
select * from sys.database_role_members --数据库角色成员
select * from sys.database_permissions --权限分配

综合上面各系统视图

/*************检查权限步骤*************/
--Step1 服务器角色中的登录名
SELECT SrvRole = g.name
      ,MemberName = u.name
      ,MemberSID = u.sid
FROM   sys.server_principals       u
      ,sys.server_principals       g
      ,sys.server_role_members     m
WHERE  g.principal_id = m.role_principal_id
       AND u.principal_id = m.member_principal_id
       and u.name not in(select name from master.sys.sql_logins where is_disabled=1)
ORDER BY 1,2
--Step2 数据库角色中的用户
SELECT DbRole = g.name
      ,MemberName = u.name
      ,MemberSID = u.sid
FROM   sys.database_principals       u
      ,sys.database_principals       g
      ,sys.database_role_members     m
WHERE  g.principal_id = m.role_principal_id
       AND u.principal_id = m.member_principal_id
ORDER BY 1,2
--Step3 服务器安全主体权限
SELECT spc.name ToObject
      ,spc.type_desc
      ,spm.class_desc
      ,spm.permission_name
      ,spm.state_desc
      ,spc1.name OnObject
FROM   sys.server_permissions spm
       INNER JOIN sys.server_principals spc
            ON  spm.grantee_principal_id = spc.principal_id
       LEFT JOIN sys.server_principals spc1
            ON  spm.major_id = spc1.principal_id
WHERE  spc.principal_id>265 --排除部分登录名
--Step4 数据库安全主体权限
SELECT dpc.name granteename
      ,OBJECT_NAME(dpm.major_id ,DB_ID()) AS objectname
      ,COL_NAME(dpm.major_id ,dpm.minor_id) AS columnname
      ,dpm.class_desc
      ,dpm.permission_name
      ,dpm.state_desc
FROM   sys.database_permissions (NOLOCK) dpm
       INNER JOIN sys.database_principals (NOLOCK) dpc
            ON  dpm.grantee_principal_id = dpc.principal_id
WHERE  dpm.grantee_principal_id >= 5 --排除public、dbo、guest、INFORMATION_SCHEMA、sys
--AND dpc.type='S'  --R角色、S用户
ORDER BY
       dpc.type,dpc.name,objectname
--Step5 查看角色(用户)被赋予的权限(数据库下)
EXEC sp_helprotect @username='DBAMonitor_ETL_V1'--username|dbrolename
EXEC sp_helprotect @name='Info_Cpu_UseLog'--tablename

我们可以针对哪些permission_name进行grant/revoke/deny

--罗列所有内置permissions
SELECT *
FROM   sys.fn_builtin_permissions(DEFAULT)
ORDER BY class_desc,permission_name;
--罗列能在object上设置的permissions
SELECT *
FROM   sys.fn_builtin_permissions('OBJECT')
ORDER BY class_desc,permission_name;

上面罗列的permission_name,都可以在实例、数据库、数据库对象右击属性的权限或安全对象页找到。

你可能感兴趣的:(数据库权限检查)