Skip to content
Fix Code Error

SQL Server query to find all permissions/access for all users in a database

March 13, 2021 by Code Error
Posted By: Anonymous

I would like to write a query on a sql 2008 that will report all the users that have access to a specific database, or objects within the database such as tables, views, and stored procedures, either directly or due to roles, etc. This report would be used for security auditing purposes. Not sure if anyone has a query that will fit my needs completely, but hopefully something that will give me a good start. Either sql 2008, 2005 or 2000 will do, I can probably convert as needed.

Solution

This is my first crack at a query, based on Andomar’s suggestions. This query is intended to provide a list of permissions that a user has either applied directly to the user account, or through
roles that the user has.

/*
Security Audit Report
1) List all access provisioned to a sql user or windows user/group directly 
2) List all access provisioned to a sql user or windows user/group through a database or application role
3) List all access provisioned to the public role

Columns Returned:
UserName        : SQL or Windows/Active Directory user account.  This could also be an Active Directory group.
UserType        : Value will be either 'SQL User' or 'Windows User'.  This reflects the type of user defined for the 
                  SQL Server user account.
DatabaseUserName: Name of the associated user as defined in the database user account.  The database user may not be the
                  same as the server user.
Role            : The role name.  This will be null if the associated permissions to the object are defined at directly
                  on the user account, otherwise this will be the name of the role that the user is a member of.
PermissionType  : Type of permissions the user/role has on an object. Examples could include CONNECT, EXECUTE, SELECT
                  DELETE, INSERT, ALTER, CONTROL, TAKE OWNERSHIP, VIEW DEFINITION, etc.
                  This value may not be populated for all roles.  Some built in roles have implicit permission
                  definitions.
PermissionState : Reflects the state of the permission type, examples could include GRANT, DENY, etc.
                  This value may not be populated for all roles.  Some built in roles have implicit permission
                  definitions.
ObjectType      : Type of object the user/role is assigned permissions on.  Examples could include USER_TABLE, 
                  SQL_SCALAR_FUNCTION, SQL_INLINE_TABLE_VALUED_FUNCTION, SQL_STORED_PROCEDURE, VIEW, etc.   
                  This value may not be populated for all roles.  Some built in roles have implicit permission
                  definitions.          
ObjectName      : Name of the object that the user/role is assigned permissions on.  
                  This value may not be populated for all roles.  Some built in roles have implicit permission
                  definitions.
ColumnName      : Name of the column of the object that the user/role is assigned permissions on. This value
                  is only populated if the object is a table, view or a table value function.                 
*/

--List all access provisioned to a sql user or windows user/group directly 
SELECT  
    [UserName] = CASE princ.[type] 
                    WHEN 'S' THEN princ.[name]
                    WHEN 'U' THEN ulogin.[name] COLLATE Latin1_General_CI_AI
                 END,
    [UserType] = CASE princ.[type]
                    WHEN 'S' THEN 'SQL User'
                    WHEN 'U' THEN 'Windows User'
                 END,  
    [DatabaseUserName] = princ.[name],       
    [Role] = null,      
    [PermissionType] = perm.[permission_name],       
    [PermissionState] = perm.[state_desc],       
    [ObjectType] = obj.type_desc,--perm.[class_desc],       
    [ObjectName] = OBJECT_NAME(perm.major_id),
    [ColumnName] = col.[name]
FROM    
    --database user
    sys.database_principals princ  
LEFT JOIN
    --Login accounts
    sys.login_token ulogin on princ.[sid] = ulogin.[sid]
LEFT JOIN        
    --Permissions
    sys.database_permissions perm ON perm.[grantee_principal_id] = princ.[principal_id]
LEFT JOIN
    --Table columns
    sys.columns col ON col.[object_id] = perm.major_id 
                    AND col.[column_id] = perm.[minor_id]
LEFT JOIN
    sys.objects obj ON perm.[major_id] = obj.[object_id]
WHERE 
    princ.[type] in ('S','U')
UNION
--List all access provisioned to a sql user or windows user/group through a database or application role
SELECT  
    [UserName] = CASE memberprinc.[type] 
                    WHEN 'S' THEN memberprinc.[name]
                    WHEN 'U' THEN ulogin.[name] COLLATE Latin1_General_CI_AI
                 END,
    [UserType] = CASE memberprinc.[type]
                    WHEN 'S' THEN 'SQL User'
                    WHEN 'U' THEN 'Windows User'
                 END, 
    [DatabaseUserName] = memberprinc.[name],   
    [Role] = roleprinc.[name],      
    [PermissionType] = perm.[permission_name],       
    [PermissionState] = perm.[state_desc],       
    [ObjectType] = obj.type_desc,--perm.[class_desc],   
    [ObjectName] = OBJECT_NAME(perm.major_id),
    [ColumnName] = col.[name]
FROM    
    --Role/member associations
    sys.database_role_members members
JOIN
    --Roles
    sys.database_principals roleprinc ON roleprinc.[principal_id] = members.[role_principal_id]
JOIN
    --Role members (database users)
    sys.database_principals memberprinc ON memberprinc.[principal_id] = members.[member_principal_id]
LEFT JOIN
    --Login accounts
    sys.login_token ulogin on memberprinc.[sid] = ulogin.[sid]
LEFT JOIN        
    --Permissions
    sys.database_permissions perm ON perm.[grantee_principal_id] = roleprinc.[principal_id]
LEFT JOIN
    --Table columns
    sys.columns col on col.[object_id] = perm.major_id 
                    AND col.[column_id] = perm.[minor_id]
LEFT JOIN
    sys.objects obj ON perm.[major_id] = obj.[object_id]
UNION
--List all access provisioned to the public role, which everyone gets by default
SELECT  
    [UserName] = '{All Users}',
    [UserType] = '{All Users}', 
    [DatabaseUserName] = '{All Users}',       
    [Role] = roleprinc.[name],      
    [PermissionType] = perm.[permission_name],       
    [PermissionState] = perm.[state_desc],       
    [ObjectType] = obj.type_desc,--perm.[class_desc],  
    [ObjectName] = OBJECT_NAME(perm.major_id),
    [ColumnName] = col.[name]
FROM    
    --Roles
    sys.database_principals roleprinc
LEFT JOIN        
    --Role permissions
    sys.database_permissions perm ON perm.[grantee_principal_id] = roleprinc.[principal_id]
LEFT JOIN
    --Table columns
    sys.columns col on col.[object_id] = perm.major_id 
                    AND col.[column_id] = perm.[minor_id]                   
JOIN 
    --All objects   
    sys.objects obj ON obj.[object_id] = perm.[major_id]
WHERE
    --Only roles
    roleprinc.[type] = 'R' AND
    --Only public role
    roleprinc.[name] = 'public' AND
    --Only objects of ours, not the MS objects
    obj.is_ms_shipped = 0
ORDER BY
    princ.[Name],
    OBJECT_NAME(perm.major_id),
    col.[name],
    perm.[permission_name],
    perm.[state_desc],
    obj.type_desc--perm.[class_desc] 
Answered By: Anonymous

Related Articles

  • Ubuntu apt-get unable to fetch packages
  • Creating a range of dates and specific time in Python
  • How to generate JAXB classes from XSD?
  • TLS 1.3 server socket with Java 11 and self-signed…
  • Problems Installing CRA & NextJS from NPM…
  • How Spring Security Filter Chain works
  • The definitive guide to form-based website authentication
  • In Pandas, how do I convert a number column to…
  • Difference between Role and GrantedAuthority in…
  • OpenIddict Roles/Policy returns 403 Forbidden
  • Requested bean is currently in creation: Is there an…
  • SQL query return data from multiple tables
  • Backbone.js - Should nested Views maintain…
  • Obtain most recent value for based on index in a…
  • Database development mistakes made by application developers
  • Does Azure AD support multi tenant user management…
  • How to setup multiple controllers in the same route…
  • Multipart File Upload Using Spring Rest Template +…
  • Secure hash and salt for PHP passwords
  • Is it possible to apply CSS to half of a character?
  • Ember.js View Binding Not Working?
  • How do i arrange images inside a div?
  • Angular2 RC5: Can't bind to 'Property X' since it…
  • An Authentication object was not found in the…
  • How to disable SSL certificate checking with Spring…
  • Select DataFrame rows between two dates
  • How to handle Vue 2 memory usage for large data (~50…
  • AngularJS ui-router login authentication
  • Spring Security exclude url patterns in security…
  • Fix top buttons on scroll of list below
  • T-SQL stored procedure that accepts multiple Id values
  • Vue-router: redirect to route if user does not have…
  • Problems using Maven and SSL behind proxy
  • PHP function outputting data out of order
  • Python sort_values (inplace=True) but not really?
  • How do I return the boolean value from this…
  • Logging best practices
  • The remote certificate is invalid according to the…
  • "PKIX path building failed" and "unable to find…
  • Spring security CORS Filter
  • Angular - error TS7030: Not all code paths return a…
  • What is a stored procedure?
  • Angular - core.js:6210 ERROR TypeError: Cannot read…
  • How to handle invalid SSL certificates with Apache…
  • PKIX path building failed in Java application
  • Start / Stop a Windows Service from a…
  • Postman gives 401 Unauthorized - Spring Boot & MYSQL
  • "The remote certificate is invalid according to the…
  • XMLHttpRequest cannot load ✘✘✘ No…
  • What's the difference between a temp table and table…
  • how can I also check if a member has a specific role…
  • Asp.net core WebApi endpoint for many to many tables
  • LDAP root query syntax to search more than one specific OU
  • java.sql.SQLException: - ORA-01000: maximum open…
  • SMTP error 554
  • Replacing blank values (white space) with NaN in pandas
  • Discord.JS, How to use one discord button to allow…
  • SecurityException: Permission denied (missing…
  • How to convert number to words in java
  • How do I execute a MS SQL Server stored procedure in…
  • How do I obtain a Query Execution Plan in SQL Server?
  • How do I count unique visitors to my site?
  • How to get active user's UserDetails
  • How should a model be structured in MVC?
  • Start redis-server with config file
  • SQL Server: Query fast, but slow from procedure
  • Iterate through a list of dicts, placing dicts…
  • Is it possible to add additional property to to…
  • Symfony find user by role (JSON array Doctrine property)
  • How can I get column names from a table in SQL Server?
  • Problem with getting all roles of the message author…
  • how to change listen port from default 7001 to…
  • How to set up file permissions for Laravel?
  • How does PHP 'foreach' actually work?
  • How can I find the product GUID of an installed MSI setup?
  • Why does Spring security throw exception…
  • dynamically add and remove view to viewpager
  • How to prevent parent component from reloading when…
  • How to handle initializing and rendering subviews in…
  • Python JSON TypeError : list indices must be…
  • How should I choose an authentication library for…
  • org.hibernate.MappingException: Could not determine…
  • What is the easiest way to remove the first…
  • How to secure EmberJS or any Javascript MVC framework?
  • How to connect to local instance of SQL Server 2008 Express
  • Why not use tables for layout in HTML?
  • Rails wrong number of arguments error when…
  • Using Auto Layout in UITableView for dynamic cell…
  • Cordova: How to move file to the Download folder?
  • SecurityException during executing jnlp file…
  • RestHeart ACL - User access controls for databases
  • Advantages of SQL Server 2008 over SQL Server 2005?
  • insert tables in dataframe with years from 2000 to…
  • Interrupt an earlier timeout event in Simpy
  • Android 6.0 multiple permissions
  • What are the undocumented features and limitations…
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • TypeScript metadata reflection references other…
  • two-way binding between object attribute array (enum…
  • Spring Test & Security: How to mock authentication?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Run jar file in command prompt

Next Post:

How to save an activity state using save instance state?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error