SQL Server 2019 cross-database function call permission - sql-server

I have come across some interesting behaviour in SQL Server 2019 - it does not seem to occur in earlier versions.
If, in database1, I call a function in the same database, which calls a function in database2, which SELECTS a table in database2, I get "The SELECT permission was denied on the object '{TableName}', database '{DbName}', schema 'dbo'."
If, instead, I call the function in database2 directly (without using a function in database1), the query executes successfully.
My question is: what is the logic behind this? I don't understand why I am allowed to read a table in another database, without the SELECT permission, through a function, but not when I call that function using a function in my current database! Is it due to the function preventing the passing on of permissions? I am assuming at the moment that this is an intended change - but I don't understand the logic behind it.
Below is some code demonstrating the behaviour in a simple way.
/*******************************************
SET UP
*******************************************/
CREATE DATABASE TestDb1
GO
CREATE DATABASE TestDb2
GO
CREATE LOGIN [TestLogin] WITH PASSWORD = '123456a.'
GO
--Create users in each database and add to roles.
USE TestDb1
CREATE USER [TestUser] FOR LOGIN [TestLogin]
CREATE ROLE Db1Role
ALTER ROLE Db1Role ADD MEMBER [TestUser]
USE TestDb2
CREATE USER [TestUser] FOR LOGIN [TestLogin]
CREATE ROLE Db2Role
ALTER ROLE Db2Role ADD MEMBER [TestUser]
--Create table in db1, but do no GRANTs on it.
USE TestDb1
CREATE TABLE dbo._testDb1Table (Col1 INT)
GO
--Create a function in db1, and GRANT EXECUTE.
CREATE FUNCTION dbo._TestDb1Function()
RETURNS INT
AS
BEGIN
DECLARE #Result INT = (SELECT TOP (1) Col1 FROM dbo._testDb1Table)
RETURN #Result
END
GO
GRANT EXECUTE ON dbo._TestDb1Function TO Db1Role
GO
--Create a function in db2, and GRANT EXECUTE.
USE TestDb2
GO
CREATE FUNCTION dbo._TestDb2Function()
RETURNS INT
AS
BEGIN
DECLARE #Result INT = (SELECT TestDb1.dbo._TestDb1Function())
RETURN #Result
END
GO
GRANT EXECUTE ON dbo._TestDb2Function TO Db2Role
GO
/*******************************************
TESTS
*******************************************/
USE TestDb2
--Querying TestDb1 by calling the TestDb2 function directly works.
EXECUTE AS LOGIN = 'TestLogin'
SELECT TestDb1.dbo._TestDb1Function()
REVERT
GO
--Querying TestDb2 through a scalar function in db2 doesn't work.
--The SELECT permission was denied on the object '_testDb1Table', database 'TestDb1', schema 'dbo'.
EXECUTE AS LOGIN = 'TestLogin'
SELECT dbo._TestDb2Function()
REVERT
GO
/*******************************************
TIDY UP
*******************************************/
USE [master]
DROP LOGIN [TestLogin]
DROP DATABASE TestDb1
DROP DATABASE TestDb2

This was a bug in SQL Server 2019, caused by scalar UDF inlining.
It was fixed in SQL Server 2019 CU9 (published in February 2021).
For more details see KB4538581.

As per helpful comments by GSerg and Larnu, this behaviour appears to be caused by the scalar UDF inlining feature, added in SQL Server 2019.
It can be fixed by disabling scalar UDF inlining at the database level, in the function definition, or using a query hint.
Edit: as per the answer by Razvan Socol, this has been fixed in SQL Sever 2019 CU9.
Here is the same code as given in the original question, but with these 3 possible solutions inserted into the appropriate places (commented out). Uncommenting any of these 3 solutions allows the script to run without error in SQL Server 2019.
/*******************************************
SET UP
*******************************************/
CREATE DATABASE TestDb1
CREATE DATABASE TestDb2
GO
--SOLUTION 1: Turn off scalar UDF inlining at the database level.
--USE TestDb2
--ALTER DATABASE SCOPED CONFIGURATION SET TSQL_SCALAR_UDF_INLINING = OFF;
GO
CREATE LOGIN [TestLogin] WITH PASSWORD = '123456a.'
GO
--Create users in each database and add to roles.
USE TestDb1
CREATE USER [TestUser] FOR LOGIN [TestLogin]
CREATE ROLE Db1Role
ALTER ROLE Db1Role ADD MEMBER [TestUser]
USE TestDb2
CREATE USER [TestUser] FOR LOGIN [TestLogin]
CREATE ROLE Db2Role
ALTER ROLE Db2Role ADD MEMBER [TestUser]
--Create table in db1, but do no GRANTs on it.
USE TestDb1
CREATE TABLE dbo._testDb1Table (Col1 INT)
GO
--Create a function in db1, and GRANT EXECUTE.
CREATE FUNCTION dbo._TestDb1Function()
RETURNS INT
AS
BEGIN
DECLARE #Result INT = (SELECT TOP (1) Col1 FROM dbo._testDb1Table)
RETURN #Result
END
GO
GRANT EXECUTE ON dbo._TestDb1Function TO Db1Role
GO
--Create a function in db2, and GRANT EXECUTE.
USE TestDb2
GO
CREATE FUNCTION dbo._TestDb2Function()
RETURNS INT
--SOLUTION 2: Turn off scalar UDF inlining for the function.
--WITH INLINE = OFF
AS
BEGIN
DECLARE #Result INT = (SELECT TestDb1.dbo._TestDb1Function())
RETURN #Result
END
GO
GRANT EXECUTE ON dbo._TestDb2Function TO Db2Role
GO
/*******************************************
TESTS
*******************************************/
USE TestDb2
--Querying TestDb1 by calling the TestDb2 function directly works.
EXECUTE AS LOGIN = 'TestLogin'
SELECT TestDb1.dbo._TestDb1Function()
REVERT
GO
--Querying TestDb2 through a scalar function in db2 doesn't work.
--The SELECT permission was denied on the object '_testDb1Table', database 'TestDb1', schema 'dbo'.
EXECUTE AS LOGIN = 'TestLogin'
SELECT dbo._TestDb2Function()
--SOLUTION 3: Turn off scalar UDF inlining for the query which calls the function.
--OPTION (USE HINT('DISABLE_TSQL_SCALAR_UDF_INLINING')); --Added line
REVERT
GO
/*******************************************
TIDY UP
*******************************************/
USE [master]
DROP LOGIN [TestLogin]
DROP DATABASE TestDb1
DROP DATABASE TestDb2

Related

Why won't T-SQL Stored Procedure return from SYS.DATABASE_PRINCIPALS

Create procedure test.access
#principal_id int
with execute as owner
as
set nocount on;
begin
select * from sys.database_principals where principal_id = #principal_id
end;
I create the above procedure and execute but it returns nothing. However if I declare #principal_id as a variable, set it then run this code outside a procedure it returns the correct rows.
Why isn't it working inside the procedure?
If the owner of the test schema does not have elevated permissions, then the rows that can be seen in sys.database_principals will be limited. From the documentation
Any user can see their own user name, the system users, and the fixed database roles. To see other users, requires ALTER ANY USER, or a permission on the user. To see user-defined roles, requires ALTER ANY ROLE, or membership in the role.
In the following script I create the user test, as well as a schema test. I make the test user the owner of the test schema.
I then create a procedure in that schema with execute as owner. It will therefore execute in the context of the test user.
But the test user does not have ALTER ANY USER permission, so the rows visible in sys.database_principals are limited:
create login test with password = 'test';
create user test for login test;
go
create schema test authorization test;
go
create procedure test.access with execute as owner as
begin
select * from sys.database_principals;
end
go
exec test.access; -- returns a limited set principals
If I grant the test user the alter any user permission and then re-execute the procedure, I will get all of the users:
grant alter any user to test;
exec test.access; -- returns all users (but not user defined roles)
grant alter any role to test;
exec test.access; -- returns everyone and all roles
If the test schema is currently not owned by the correct user, you can change that:
alter authorization on schema::test to [user];

SQL Server Permission Chaining

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;

How do you give a ReadOnly User the ability to call a scalar function?

I have a user who is a member of the db_DataReader role (and no other roles apart from public), and has been granted explicit execute permission on a scalar function, but when they use the function
select hbp_plant.CatComments(42)
they get
The EXECUTE permission was denied on the object 'CatComments', database 'HBDevSIMCOA', schema 'HBP_Plant'*.
How do I give them permission to call the function without giving them any ability to modify the database?
Does the function access tables in different schemas, other than hbp_plant?
Instead of adding the db user to the db_datareader role, grant SELECT (for the whole db) and execute permissions on the function:
--db user = myreadonlyuser
grant select to myreadonlyuser; --can read from tables, table valued functions, views..in all schemas
grant execute on hbp_plant.CatComments to myreadonlyuser;
Give Exec Permission on tablename. Try this.
USE HBDevSIMCOA;
GRANT EXEC ON hbp_plant.CatComments TO PUBLIC
you can refer below link
The EXECUTE permission was denied on the object 'xxxxxxx', database 'zzzzzzz', schema 'dbo'
Try this:
CREATE SCHEMA [hbp_plant];
GO
CREATE FUNCTION [hbp_plant].[CatComments] (#A INT)
RETURNS INT
AS
BEGIN
RETURN #A
END;
GO
CREATE USER [StackOverflow] WITHOUT LOGIN;
-- do not work
EXECUTE AS USER = 'StackOverflow';
SELECT [hbp_plant].[CatComments](5) ;
REVERT;
GRANT EXECUTE ON [hbp_plant].[CatComments] TO [StackOverflow];
-- work
EXECUTE AS USER = 'StackOverflow';
SELECT [hbp_plant].[CatComments](5) ;
REVERT;
DROP USER [StackOverflow];
DROP FUNCTION [hbp_plant].[CatComments]
DROP SCHEMA [hbp_plant];

SQL Server: Is it possible to synchronize user GUIDs between two databases if the users are not tied to a login?

Our project uses SQL Server database users without logins to implement security and row-level filtering.
We have implemented a very basic form of mirroring in which the transactional database is backed up and restored nightly to a second “mirror” copy. A web service pulls data from the mirror.
However, we need to log web service requests in the transactional database so that they are not wiped out when the next mirror is restored.
We attempted to implement this by replacing the log tables in the mirror with synonyms pointing at the "real" tables in the transactional database.
However, attempts to write to the synonyms invariably fail with error messages such as:
The server principal "" is not able to access the database "" under the current security context
I’m guessing this happens because, during restore, the users are re-created and assigned new GUIDs?
I've found lots of answers that talk about re-connecting a database user to a SQL Server login using sp_change_users_login or ALTER USER, but these solutions don't seem applicable, since these database users don't have logins.
Is there some way to ensure that users in the mirrored database are recognized as the same user in the transactional database if their usernames are the same?
Thanks!
Yes, when you CREATE a USER (or LOGIN) you can define the SID when you create it:
USE DB1;
GO
CREATE USER SampleUser WITHOUT LOGIN WITH SID = 0x010500000000000903000000F759D99F7F71EC459908C0A30B39056C;
USE DB2;
GO
CREATE USER SampleUser WITHOUT LOGIN WITH SID = 0x010500000000000903000000F759D99F7F71EC459908C0A30B39056C;
Is there some way to ensure that users in the mirrored database are
recognized as the same user in the transactional database if their
usernames are the same?
The answer is:No
Users without logins are database principals only. For any users, in different dbs, to be "one" they need to "point" to the same server principal: login. It is the login that "connects" database users.
I’m guessing this happens because, during restore, the users are
re-created and assigned new GUIDs?
The SIDs (Security IDentifiers) of the database users do not change when the db is restored.
The fact that the sids do not change but remain the same, requires the actions you have found (sp_change_users_login or ALTER USER) when a database is restored to another server.
3 options for cross database actions:
cross database ownership chaining
impersonation
module signing
I cannot tell if crossdb chaining will work, since the loginless users do not have any security essence when they leave their database. Outside their database, loginless users have no security attributes, they lose their "identity".
On the other hand, impersonation and module signing can work, because the security attributes are warranted by another principal.
Following is a "simplistic" poc, for db users without login, performing cross db actions with sql-modules signed by an asymmetric key. There are plenty of examples online for module signing with certificates and the workings are the same. Most articles you'll find online, execute the signed modules in the scope of a server principal (exec as login, exec signed_module) while the loginless users have no server level existence.
Signed modules need to be executed by a trusted entity for the signature to take effect(a login is by definition trusted) and for loginless users their trustiness comes from their own db. For that, the db where the loginless users reside must be TRUSTWORTHY ON.
In the poc, there is a signed multiline table valued function in the mirrordb which is used for selecting data from the transactional db. The function is the base for a view (views cannot be signed). The view is the target of DML. The actual dml action(s) are performed by signed INSTEAD OF triggers.
You need to generate&adjust the path to the asymmetric key before executing the script.
Impersonation could work the same way(take away the signing related actions and create each module with EXECUTE AS)
create database transactionaldb
go
create database mirrordb
go
--target table in transactionaldb
use transactionaldb
go
create table targettable
(
id int identity,
username nvarchar(128) default(user_name()),
somevalue varchar(10),
thedate datetime default(getdate())
)
go
--mirror db, userwithout login
use mirrordb
go
create user userwithoutlogin without login
go
--synonym, just for testing
create synonym targettablesynonym for transactionaldb..targettable
go
--for testing, grant permissions on synonym to loginless user
grant select, insert, update, delete on targettablesynonym to userwithoutlogin
go
--switch to loginless user and select from synonym
execute as user = 'userwithoutlogin'
go
select * from targettablesynonym --The server principal "S-1-2-3-4..." is not able to access the database "transactionaldb" under the current security context.
go
--revert
revert
go
/*
1) cross db ownership chaining
2) impersonation
3) module signing (below)
*/
--module signing, asymmetric key
--create a strong key/name file using sn.exe : sn -k 2048 c:\testdata\asymkeytest.snk //use key size 2048 for sql2016 on.
--the same for transactionaldb
use transactionaldb
go
--master key transactionaldb
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'M#st3rkeyTransactional'
GO
CREATE ASYMMETRIC KEY asymkeytest
AUTHORIZATION dbo
FROM FILE = 'c:\testdata\asymkeytest.snk';
GO
create user asymkeytransactionaldbuser from asymmetric key asymkeytest
go
--grant permissions on targettable to asymkeytransactionaldbuser
grant select, insert, update, delete on targettable to asymkeytransactionaldbuser;
go
use mirrordb
go
--master key mirrordb
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'M#st3rkeyMirror'
GO
CREATE ASYMMETRIC KEY asymkeytest
AUTHORIZATION dbo
FROM FILE = 'c:\testdata\asymkeytest.snk';
GO
--a db user from the asymkey? not really needed
--create user asymkeymirrordbuser from asymmetric key asymkeytest
go
select is_master_key_encrypted_by_server, *
from sys.databases
where name in ('transactionaldb', 'mirrordb');
go
use mirrordb
go
--a function in mirror which reads the table from transactional
create or alter function dbo.fnreadtargettablefromtransactionaldb()
returns #result table
(
id int,
username nvarchar(128),
somevalue varchar(10),
thedate datetime
)
as
begin
insert into #result(id, username, somevalue, thedate)
select id, username, somevalue, thedate
from transactionaldb.dbo.targettable;
return;
end
go
--grant select on loginless user
grant select on fnreadtargettablefromtransactionaldb to userwithoutlogin;
go
--switch to loginless user and select from function
execute as user = 'userwithoutlogin'
go
select * from fnreadtargettablefromtransactionaldb(); --The server principal "S-1-2-3-4..." is not able to access the database "transactionaldb" under the current security context.
go
--revert
revert
go
--sign the function with the asymmetric key
add signature to fnreadtargettablefromtransactionaldb by ASYMMETRIC KEY asymkeytest;
--... after signing
execute as user = 'userwithoutlogin'
go
select * from fnreadtargettablefromtransactionaldb(); --The server principal "S-1-2-3-4..." is not able to access the database "transactionaldb" under the current security context.
go
--revert
revert
go
--the signed module/function is accessing the transactionaldb but it is NOT trusted
--it could be trusted if:
-- a. it was called in the context of a server principal (login, by definition it is trusted)
-- b. if the source db of the signed module is trustful
--make the source db of the signed module trustful
alter database mirrordb set trustworthy on;
--test again
execute as user = 'userwithoutlogin'
go
--synonym (needs permissions now, at the destination)
select * from targettablesynonym
--signed function, working, permissions from the asymmetric key
select * from fnreadtargettablefromtransactionaldb(); --works
go
--revert
revert
go
use mirrordb
go
--complete interface
create or alter view transactiontableview
as
select *
from fnreadtargettablefromtransactionaldb()
go
--view permissions
grant select, insert, update, delete on transactiontableview to userwithoutlogin;
go
--instead of insert trigger
create or alter trigger insteadofinsertonview on transactiontableview instead of insert
as
begin
set nocount on;
if not exists(select * from inserted)
begin
return;
end
insert into transactionaldb.dbo.targettable(username, somevalue, thedate)
select user_name(), somevalue, thedate
from inserted;
end
go
--sign
add signature to insteadofinsertonview by ASYMMETRIC KEY asymkeytest;
go
execute as user = 'userwithoutlogin'
go
insert into transactiontableview(somevalue)
select col
from (values('one'), ('2'), ('3')) as t(col);
select * from transactiontableview
go
--revert
revert
go
/***********************************************/
--check the security token of a signed module when db trustworthy is off
alter database mirrordb set trustworthy off;
go
--create a proc
create or alter procedure showsecuritytokens
as
begin
select 'mirror_db' as dbname, *
from mirrordb.sys.user_token
union all
select 'transactional_db' as dbname, *
from transactionaldb.sys.user_token;
end
go
--sign the proc for accessing transactionaldb info
add signature to showsecuritytokens by ASYMMETRIC KEY asymkeytest;
go
--permissions
grant execute on showsecuritytokens to userwithoutlogin
go
--enable guest for transactionaldb
use transactionaldb
go
grant connect to guest
go
use mirrordb
go
--switch to loginless user
execute as user = 'userwithoutlogin'
go
exec showsecuritytokens
--when from an untrusted source: the signed module does not get the GRANTs of the asymmetric key (at the destination)
/*
thedb_______________principal_id__name_________________________type___________________________usage
transactional_db____5_____________asymkeytransactionaldbuser___USER MAPPED TO ASYMMETRIC KEY__DENY ONLY
*/
go
--revert
revert
go
--cleanup
/*
use master
go
drop database transactionaldb
go
drop database mirrordb
go
*/

Grant CREATE TABLE permission only on database but not ALTER

Just trying to play around with permissions, I want to grant CREATE table permission to user but not ALTER or DROP. Moreover user should be able to create table only(no stored proc, no function)
grant alter on schema::dbo to demo_db_user
grant create table to demo_db_user
By using above command, user is able to alter table as well.
You could write a DDL-Trigger and prevent the ALTER TABLE if the current User is not member in a specific role (or whatever), similar like this (untested):
CREATE TRIGGER [ddl_tr_prvent_alter_table] ON DATABASE
FOR alter_procedure
as
begin
if User_Name() <> 'dbo'
RAISERROR ('go ahead, you must not change a table', 16, 1);
end

Resources