Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MS SQL Server: Check to see if a user can execute a stored procedure

How can you check to see if a user can execute a stored procedure in MS SQL server?

I can see if the user has explicit execute permissions by connecting to the master database and executing:

databasename..sp_helpprotect 'storedProcedureName', 'username'

however if the user is a member of a role that has execute permissions sp_helprotect won't help me.

Ideally I'd like to be able to call something like

databasename..sp_canexecute 'storedProcedureName', 'username'

which would return a bool.

like image 397
Andrew Avatar asked Jan 27 '09 16:01

Andrew


3 Answers

Try something like this:

CREATE PROCEDURE [dbo].[sp_canexecute]
@procedure_name varchar(255),
@username varchar(255),
@has_execute_permissions bit OUTPUT
AS

IF EXISTS (
        /* Explicit permission */
        SELECT 1
        FROM sys.database_permissions p
        INNER JOIN sys.all_objects o ON p.major_id = o.[object_id] AND o.[name] = @procedure_name
        INNER JOIN sys.database_principals dp ON p.grantee_principal_id = dp.principal_id AND dp.[name] = @username
    )
    OR EXISTS (
        /* Role-based permission */
        SELECT 1
        FROM sys.database_permissions p
        INNER JOIN sys.all_objects o ON p.major_id = o.[object_id]
        INNER JOIN sys.database_principals dp ON p.grantee_principal_id = dp.principal_id AND o.[name] = @procedure_name
        INNER JOIN sys.database_role_members drm ON dp.principal_id = drm.role_principal_id
        INNER JOIN sys.database_principals dp2 ON drm.member_principal_id = dp2.principal_id AND dp2.[name] = @username
    )
BEGIN
    SET @has_execute_permissions = 1
END
ELSE
BEGIN
    SET @has_execute_permissions = 0
END
GO
like image 31
Dane Avatar answered Sep 29 '22 09:09

Dane


fn_my_permissions and HAS_PERMS_BY_NAME

like image 95
Cade Roux Avatar answered Sep 29 '22 10:09

Cade Roux


Assuming the SP only runs a SELECT statement:

EXECUTE AS USER = [User's ID/Login]
EXEC sp_foobar( sna, fu)
REVERT

It's important to note that you will need to run the REVERT command after the prompt as SQL Server will regard you as the user you are EXECUTING AS until you either shut down the connection or REVERT the impersonation. That said, you should see exactly what a user would get (getting some rows but not all? This should help you out).

like image 40
Pulsehead Avatar answered Sep 29 '22 11:09

Pulsehead