I am not quite clear about the difference between different EXECUTE AS targets in SQL Server : CALLER, SELF and OWNER, notably between the last two.
My understanding is that CALLER is the one who Execute/Call the procedure.
SELF is the specified user is the person creating or altering the module
OWNER is the current owner of the module
Could you explain and give some example who is the person creating/modifying and the owner of the module. Is 'module' here the stored procedure/function or the session or the database ? Including an example with SELF user will be great.
Being put very simple, SELF impersonates you as a database user who actually executed create / alter procedure the last time. It doesn't always have to be the schema owner, as you can imagine, it can be any person with permissions sufficient to create / modify given objects.
The OWNER mode impersonates you as the owner of the schema the procedure / function belongs to.
If you want to dig a little deeper (and is this case, there is always some room to dig in), below is a (relatively) simple example that can demonstrate you how things can work here. There are some shortcuts and implications that are specific to SQL Server which I omit deliberately because otherwise it would be too much to write. You can always read the documentation, though.
use master;
go
if db_id('TestDB') is not null
drop database TestDB;
go
create database TestDB;
go
use TestDB;
go
-- Just for the sake of example, so that everyone can create procs
grant create procedure to public;
go
-- Schema owner
create user [SomeUser] without login;
go
create schema [s1] authorization [SomeUser];
go
-- An ordinary user
create user [AnotherUser] without login;
go
grant execute on schema::s1 to AnotherUser as [SomeUser];
go
-- Database administrator
create user [DBA] without login;
go
alter role [db_owner] add member [DBA];
go
-- Although it's SomeUser that owns the schema, DBA creates objects in it
execute as user = 'DBA';
go
create procedure s1.SpCaller
as
select user_name() as [s1_caller];
return;
go
create procedure s1.SpSelf
with execute as self as
select user_name() as [s1_self];
return;
go
create procedure s1.SpOwner
with execute as owner as
select user_name() as [s1_owner];
return;
go
revert;
go
-- You can play with actual impersonation and look at results
execute as user = 'AnotherUser';
go
exec s1.SpCaller;
go
exec s1.SpSelf;
go
exec s1.SpOwner;
go
revert;
go
Related
I have the following issue:
I have two different databases, db1 and db2. I have an application that loads data into db2 or db3. db1 has a few tables that the application uses to determine behavior, including which db the application should load data into.
Users need to have write access to db1 to operate the application (there is a console application that writes to tables in db1, operating with windows authentication).
Users should not have DML privileges to db2 and db3, with the exception of a few predetermined operations. We grant AD groups database roles to control access from and organization perspective. Specifically, I'm trying to build a stored procedure in db1 that operators can use to reverse data loaded to db2 or db3 with appropriate logging.
I'm attempting to use create proc ... execute as owner to accomplish this, but it does not seem to be working when I try to hit tables in db2/db3 (I'm thinking that "execute as owner" operates on db level users an not server level logins?). The following causes a permission error stating that the owner (myself) does not have permissions to db2/db3.
use db1
go
create proc dbo.wrapper #recordid int
as begin
/*
capturing user
*/
declare #usr varchar(255) = SUSER_SNAME()
exec dbo.inner #usr , #recordid
end
use db1
go
create proc dbo.inner #usr varchar(255), #recordid int
with execute as owner
as begin
/*
logic to determine whether to update db2 or db3 goes here
*/
insert db2.rolled_back
select * , #usr from db2.transactions where id = #recordid
delete from db2.transactions where id = #recordid
insert db3.rolled_back
select * , #usr from db3.transactions where id = #recordid
delete from db3.transactions where id = #recordid
end
Is there a way to get this to work? I've heard that certificate signing could do this, does anyone have any experience using certificate users. Our DBA's would rather not have to maintain certificates, so if there is a way to get this to work without certificates that would be best.
Any advice would be helpful.
Thank You!
I'm going to cover the cross database chaining side of thing here. note that there are certainly security considerations when using this method. For example someone with permissions to create objects in one database can give themselves access to data in another database with the owner, when they themselves have no access to the other database. The security concerns, however, are out of scope of this answer.
Firstly, let's create a couple of test databases.
USE master;
GO
CREATE DATABASE Chain1;
CREATE DATABASE Chain2;
Now I'm going to CREATE a LOGIN, which is disable and make that the owner of these 2 databases. The databases having the same owner is important, as otherwise the chaining won't work.
CREATE LOGIN ChainerOwner WITH PASSWORD = N'SomeSecurePassword123';
ALTER LOGIN ChainerOwner DISABLE;
GO
ALTER AUTHORIZATION ON DATABASE::Chain1 TO ChainerOwner;
ALTER AUTHORIZATION ON DATABASE::Chain2 TO ChainerOwner;
I'm also going to create a LOGIN which we're going to use to test on:
CREATE LOGIN SomeUser WITH PASSWORD = N'SomeSecurePassword123';
Great, now I can create a few objects; a table in Chain1, a PROCEDURE in Chain2 that accesses the TABLE, and a USER in both databases for SomeUser. In Chain1 the USER will be given no permissions, and in Chain2 the user will be given the permsision to EXECUTE the PROCEDURE:
USE Chain1;
GO
CREATE TABLE dbo.SomeTable (I int IDENTITY,
S varchar(10));
INSERT INTO dbo.SomeTable (S)
VALUES ('abc'),
('xyz');
GO
CREATE USER SomeUser FOR LOGIN SomeUser;
GO
USE Chain2;
GO
CREATE PROC dbo.CrossDBProc #I int AS
BEGIN
SELECT I,
S
FROM Chain1.dbo.SomeTable
WHERE I = #I;
END;
GO
CREATE USER SomeUser FOR LOGIN SomeUser;
GO
GRANT EXECUTE ON dbo.CrossDBProc TO SomeUser;
GO
Great, all the objects are created, now let's try to EXECUTE that PROCEDURE:
EXECUTE AS LOGIN = 'SomeUser';
GO
EXEC dbo.CrossDBProc 1; --This fails
GO
REVERT;
GO
This fails, with a permission error:
The SELECT permission was denied on the object 'SomeTable', database 'Chain1', schema 'dbo'.
This is expected, as there is no ownership chaining. let's, therefore enable that now.
USE master;
GO
ALTER DATABASE Chain1 SET DB_CHAINING ON;
ALTER DATABASE Chain2 SET DB_CHAINING ON;
Now if I try the same again, the same SQL works:
USE Chain2;
GO
EXECUTE AS LOGIN = 'SomeUser';
GO
EXEC dbo.CrossDBProc 1; --This now works
GO
REVERT;
GO
This successfully returns the result set
I
S
1
abc
So, yes you can chain cross database, but it requires some set up, and (again) there are security considerations you need think about.
Clean up:
USE master;
GO
DROP DATABASE Chain1;
DROP DATABASE Chain2;
GO
DROP LOGIN ChainerOwner;
DROP LOGIN SomeUser;
The only user that can see the entire sys.sysprocesses is the SA. Is there a role I can place a user (or any other way) that a user can be made a member of so the user can see the entire sys.sysprocesses -all the rows for all users not just the processes for the user executing the select.
I connect to many SQL Server instances with a dbo account. I need to know if someone is connected to the instance. I cannot get SA privileges.
You can use code signing to accomplish what you're looking to do. Here's the code:
CREATE LOGIN [normalUser] WITH password = 'f00bar!23'
CREATE USER [normalUser]
GO
CREATE CERTIFICATE [codeSigningCert] WITH SUBJECT = 'Certificate for code signing', EXPIRY_DATE = '2099-01-01'
CREATE LOGIN [codeSigningLogin] FROM CERTIFICATE [codeSigningCert]
GRANT VIEW SERVER STATE TO [codeSigningLogin]
go
CREATE PROCEDURE dbo.processesProc
AS
BEGIN
SELECT *
FROM sys.sysprocesses AS s
END
GO
GRANT EXECUTE ON dbo.processesProc TO [normalUser]
GO
EXECUTE AS LOGIN = 'normalUser'
GO
EXEC dbo.processesProc
GO
REVERT
GO
ADD SIGNATURE TO processesProc BY CERTIFICATE [codeSigningCert]
GO
GRANT EXECUTE ON dbo.processesProc TO [normalUser]
GO
EXECUTE AS LOGIN = 'normalUser'
GO
EXEC dbo.processesProc
GO
REVERT
GO
By way of explanation, I'm creating an unprivileged login/user and a stored procedure for them to run. Without signing the procedure, the select exhibits the normal behavior (that is, it only displays the current process. But once I add a signature to the procedure using a certificate that has an associated login with the proper permissions, the result set blossoms.
Note: I created the procedure in master because I'm lazy. You can create the procedure anywhere you want so long as the certificate exists in the database you're creating the procedure in (so you can add the signature). Lastly, one gotacha with code signing is that the signature is lost when the procedure is modified. This makes sense as the signature is an attestation of the contents of the proc at the time of signing. If the body is changed, it will need to be re-signed.
I'm trying to figure out if there is a way to achieve the converse of this:
can a SQL Server stored proc execute with higher permission than its caller?
I want to create a stored procedure which does one thing if the user is in a role, but a fallback option if they're not.
My first attempt tried to query the current user's roles, based on this:
How to query current user's roles
I tried to query what role a user was in, and decide what to do based on that. But if you set "mydomain\Domain Users" to a role (for example), users who belong to Domain Users aren't listed in the sys.database_role_members view. So users who were supposed to have permissions don't.
From here https://msdn.microsoft.com/en-us/library/ee677633.aspx
IS_ROLEMEMBER always returns 0 when a Windows group is used as the database
principal argument, and this Windows group is a member of another Windows
group which is, in turn, a member of the specified database role.
My next attempt works like this. Create a stored procedure with the actual permissions, and then a wrapper around it which calls the with lower permissions, and if that fails, perform the fallback action:
CREATE PROCEDURE [internal_myproc]
AS
BEGIN
-- do something here
END
GO
GRANT EXECUTE ON [internal_myproc] TO [Role1] AS [dbo]
GO
CREATE PROCEDURE [myproc]
AS
BEGIN
BEGIN TRY
EXEC [internal_myproc]
END TRY
BEGIN CATCH
-- perform fallback action
END CATCH
END
GO
GRANT EXECUTE ON [internal_myproc] TO [Role1] AS [dbo]
GO
GRANT EXECUTE ON [internal_myproc] TO [Role2] AS [dbo]
GO
GRANT EXECUTE ON [internal_myproc] TO [Role3] AS [dbo]
GO
The problem with this is that [Role1] and [Role2] both succeed in executing [internal_myproc] via [myproc]. If you take the code out of the stored procedure, it behaves the way it should, but because it's hidden inside a stored procedure, it gets implicit permissions to execute other stored procedures. I've experimented with "WITH EXECUTE AS" stuff, but it doesn't seem to change anything.
I also tried "IF HAS_PERMS_BY_NAME('internal_myproc', 'OBJECT', 'EXECUTE') = 1", suggested here MS SQL Server: Check to see if a user can execute a stored procedure , but that seems to not work in certain situations I haven't understood yet.
Is there a way to NOT grant those implicit permissions, to do a permission check inside a stored procedure? Or something equivalent?
For a .net application we can store database connectionstrings like so
<connectionstrings config="cnn.config" />
I am trying to get as little as permissions as possible but there always seems to be a different way. To get info.
I am using the settings because they are more secure for one and two I have other people working on my application.
So I've set
USE database_name;
GRANT EXECUTE TO [security_account];
So the user can execute commands that's fine.
Then I've got db_reader and db_writer so they can read and write and this seems like a perfect marriage.
Still bad news the user can login and see the tables and store procedures definitions but not alter them, however, they can still see them.
How can I set the permissions to where the user can read, write. execute, and that is it PERIOD!?
Being able to see the definition of tables, stored procedures, etc is governed by the VIEW DEFINITION permission. So you can do:
DENY VIEW DEFINITION TO [yourUser];
And that user won't be able to see the definition for any object in the database. This also includes the ability to see other users.
If you want to stop the user from viewing the sp definition you need to specify the WITH ENCRYPTION option in the sp.
Adding a user to the db_datareader and db_datawriter role and granting EXECUTE will limit the user to reading writing and executing but they will still be able to see the sp definition by using the sp_helptext stored procedure and sys.sql_modules catalog view. See here for more information on sp and funciton encryption.
exec sp_addrolemember #rolename = 'db_datareader', #membername = 'testUser'
exec sp_addrolemember #rolename = 'db_datawriter', #membername = 'testUser'
GRANT EXECUTE TO testUser;
You can create an sp the WITH ENCRYPTION option by adding it before the AS keyword like this. See the WITH ENCRYPTION section of the CREATE PROCEDURE definition here
CREATE PROCEDURE HumanResources.uspEncryptThis
WITH ENCRYPTION
AS
SET NOCOUNT ON;
SELECT BusinessEntityID, JobTitle, NationalIDNumber, VacationHours, SickLeaveHours
FROM HumanResources.Employee;
GO
You can also alter functions by adding it after the returns keyword.
ALTER FUNCTION dbo.getHash ( #inputString VARCHAR(20) )
RETURNS VARBINARY(8000) WITH ENCRYPTION
I created a stored procedure which performs a series of operations that require special permissions, e.g. create database, restore database, etc. I create this stored procedure with
execute as self
...so that it runs as SA. This is because I want to give a SQL user without any permissions the ability to run only these commands which I have defined.
But when I run this stored proc, I get
The server principal "sa" is not able to access the database "model" under the current security context.
How come SA can't access the model database? I actually ran the code in the stored proc on its own, under SA, and it ran fine.
Read Extending Database Impersonation by Using EXECUTE AS before you continue.
when impersonating a principal by using the EXECUTE AS USER statement,
or within a database-scoped module by using the EXECUTE AS clause, the
scope of impersonation is restricted to the database by default. This
means that references to objects outside the scope of the database
will return an error.
You need to use module signing. Here is an example.
For anybody else coming here looking for this info, here is sample code that demonstrates exactly what OP (and I) wanted (based on excellent info from Remus above):
-- how to sign a stored procedure so it can access other Databases on same server
-- adapted from this very helpful article
-- http://rusanu.com/2006/03/01/signing-an-activated-procedure/
USE [master]
GO
CREATE DATABASE TempDB1
CREATE DATABASE OtherDB2
GO
USE TempDB1
GO
-- create a user for TempDB1
CREATE USER [foo] WITHOUT LOGIN
GO
CREATE PROCEDURE TempDB1_SP
AS
BEGIN
CREATE TABLE OtherDB2.dbo.TestTable (ID int NULL)
IF ##ERROR=0 PRINT 'Successfully created table.'
END
GO
GRANT EXECUTE ON dbo.TempDB1_SP TO [foo]
GO
EXECUTE AS User='foo'
PRINT 'Try to run an SP that accesses another database:'
EXECUTE dbo.TempDB1_SP
GO
REVERT
-- Output: Msg 916, Level 14, State 1, Procedure TempDB1_SP, Line 5
-- [Batch Start Line 14]
-- The server principal "..." is not able to access the database
-- "OtherDB2" under the current security context.
PRINT ''
PRINT 'Fix: Try again with signed SP...'
-- Create cert with private key to sign the SP with.
-- Password not important, will drop private key
USE TempDB1
GO
-- create a self-signed cert
CREATE CERTIFICATE [DB_Cert]
ENCRYPTION BY PASSWORD = 'Password1'
WITH SUBJECT = 'Signing for cross-DB SPs';
-- Sign the procedure with the certificate’s private key
ADD SIGNATURE TO OBJECT::[TempDB1_SP]
BY CERTIFICATE [DB_Cert]
WITH PASSWORD = 'Password1'
-- Drop the private key. This way it cannot be used again to sign other procedures.
ALTER CERTIFICATE [DB_Cert] REMOVE PRIVATE KEY
-- Copy the public key part of the cert to [master] database
-- backup to a file and create cert from file in [master]
BACKUP CERTIFICATE [DB_Cert] TO FILE = 'C:\Users\Public\DBCert.cer'
USE [OtherDB2] -- or use [master] = all DBs on server accessible
GO
CREATE CERTIFICATE [DB_Cert] FROM FILE = 'C:\Users\Public\DBCert.cer';
-- the 'certificate user' carries the permissions that are automatically granted
-- when the signed SP accesses other Databases
CREATE USER [DB_CertUser] FROM CERTIFICATE [DB_Cert]
GRANT CREATE TABLE TO [DB_CertUser] -- or whatever other permissions are needed
GO
USE TempDB1
EXECUTE dbo.TempDB1_SP
GO
-- output: 'Successfully created table.'
-- clean up: everything except the cert file, have to delete that yourself sorry
USE [master]
GO
DROP DATABASE TempDB1
DROP DATABASE OtherDB2
GO