SQL Server 2016. There's a view in the database A that makes a selection from a table in another database, B:
use A
go
create view TheView as
select * from B.dbo.SomeTable
I have dbo access to the B database, and I can query the view all I want:
select * from TheView -- Works as expected
Now I've created a procedure with EXECUTE AS SELF clause, hoping it will execute as me:
use A
go
create proc dbo.f
with execute as self
as
select * from TheView
When I run it, I get the following:
The server principal "ACME\seva" is not able to access the database "B" under the current security context.
If I remove the execute as clause, the procedure runs as expected.
I'm connecting with a Windows domain account, using integrated security.
What am I missing here?
EXECUTE AS impersonation is sandboxed to the current database unless the database is set to TRUSTWORTHY. Rather than turning on the TRUSTWORTHY database option, consider a less heavy-handed approach to extending security across databases. Methods to provide a non-privileged user permissions across databases include:
DB_CHAINING:
DB_CHAINING ON allows standard intra-database ownership chaining to extend across databases so that permissions on indirectly accessed objects are not required. Users need only execute permissions on your dbo.f stored procedure as long as the ownership chaining is unbroken. Note that users will still to be a user in database B but no object permissions need be granted. For example:
ALTER DATABASE A SET DB_CHAINING ON;
ALTER DATABASE B SET DB_CHAINING ON;
The implication with DB_CHAINING and dbo-owned objects is that both database A and B must be owned by the same login in order to maintain an unbroken ownership chain for the dbo user. The database owner(s) can be changed using ALTER AUTHORIZATION if needed:
ALTER AUTHORIZATION ON DATABASE::A to DatabaseOwnerLogin;
ALTER AUTHORIZATION ON DATABASE::B to DatabaseOwnerLogin;
Module Signing:
Module signing allows one to add additional permissions to a module via a certificate user. Create a certificate, create a user from the certificate, grant the certificate user the needed permissions, and then sign the stored procedure with the certificate. Below is sample code gleaned from this article.
An advantage of module signing over DB_CHAINING is that the calling user does not need to have be a user in database B because the cert user provides the security context. Be aware that the proc will need to be re-signed if it is later altered.
USE B;
-- create certifciate, cert user, and grant needed permissions
CREATE CERTIFICATE cross_database_cert
ENCRYPTION BY PASSWORD = 'All you need is love'
WITH SUBJECT = 'For cross-database access';
CREATE USER cross_database_cert FROM CERTIFICATE cross_database_cert;
GRANT SELECT ON dbo.SomeTable TO cross_database_cert;
GO
-- Copy cert to database A
DECLARE #cert_id int = cert_id('cross_database_cert')
DECLARE #public_key varbinary(MAX) = certencoded(#cert_id),
#private_key varbinary(MAX) =
certprivatekey(#cert_id,
'All you need is love',
'All you need is love')
SELECT #cert_id, #public_key, #private_key
DECLARE #sql nvarchar(MAX) =
'CREATE CERTIFICATE cross_database_cert
FROM BINARY = ' + convert(varchar(MAX), #public_key, 1) + '
WITH PRIVATE KEY (BINARY = ' +
convert(varchar(MAX), #private_key, 1) + ',
DECRYPTION BY PASSWORD = ''All you need is love'',
ENCRYPTION BY PASSWORD = ''All you need is love'')'
EXEC A.sys.sp_executesql #sql;
GO
ALTER CERTIFICATE cross_database_cert REMOVE PRIVATE KEY;
GO
USE A;
GO
--sign proc with certificate
ADD SIGNATURE TO dbo.f BY CERTIFICATE cross_database_cert
WITH PASSWORD = 'All you need is love';
GO
ALTER CERTIFICATE cross_database_cert REMOVE PRIVATE KEY;
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;
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
*/
I have created a testuser login set as sysdamin, and used it for the clause execute as in the following function created in a test database other than the msdb.
CREATE FUNCTION [dbo].[MyTestFunction]
(#job_name SYSNAME)
RETURNS INT
WITH EXECUTE AS 'TestUser'
AS
BEGIN
DECLARE #id INT
SELECT TOP 1 #id = schedule_id
FROM msdb.dbo.sysjobschedules
RETURN #id
END
When I execute MyTestFunction I get the following error:
The SELECT permission was denied on the object 'sysjobschedules', database 'msdb', schema 'dbo'.
In change, if I directly log in with the TestUser login and straight execute the SELECT statement using the test database, it works fine.
User TestUser can directly access msdb from the test database, but can't access msdb if used in the execute as clause of a function of the test database.
How can I access the msdb database from a function created in another database?
The EXECUTE AS impersonated security context is sandboxed to the current database. You cannot access other databases within the function unless the database is TRUSTWORTHY, which is not generally a good practice.
For cross-database access by minimally privileged users, consider using module signing. This allows you to grant access to other databases and objects within the module execution context without granting the end user direct permissions. Users only need permissions on the function.
Below is an example script gleaned from the referenced article for your particular need. Although this basic technique could be extended to provide sysadmin permissions, the best practice is to use a minimally privileged account.
-- Create a certificate in msdb
USE msdb;
CREATE CERTIFICATE msdb_certificate
ENCRYPTION BY PASSWORD = 'p#Ss0RDforTheceRT1cate'
WITH SUBJECT = 'For cross-database access to msdb database';
-- create a user from certification with needed permissions
CREATE USER msdb_certificate_user FROM CERTIFICATE msdb_certificate;
GRANT SELECT ON msdb.dbo.sysjobschedules TO msdb_certificate_user;
-- Copy certificate to user database (Example)
DECLARE #cert_id int = cert_id('msdb_certificate');
DECLARE #public_key varbinary(MAX) = certencoded(#cert_id),
#private_key varbinary(MAX) =
certprivatekey(#cert_id,
'p#Ss0RDforTheceRT1cate',
'p#Ss0RDforTheceRT1cate');
DECLARE #sql nvarchar(MAX) =
'CREATE CERTIFICATE msdb_certificate
FROM BINARY = ' + convert(varchar(MAX), #public_key, 1) + '
WITH PRIVATE KEY (BINARY = ' +
convert(varchar(MAX), #private_key, 1) + ',
DECRYPTION BY PASSWORD = ''p#Ss0RDforTheceRT1cate'',
ENCRYPTION BY PASSWORD = ''p#Ss0RDforTheceRT1cate'')';
EXEC YourDatabase.sys.sp_executesql #sql;
ALTER CERTIFICATE msdb_certificate REMOVE PRIVATE KEY; --remove ephemeral private key
GO
--sign module with certificate
USE YourDatabase;
ADD SIGNATURE TO dbo.MyTestFunction BY CERTIFICATE msdb_certificate
WITH PASSWORD = 'p#Ss0RDforTheceRT1cate';
ALTER CERTIFICATE msdb_certificate REMOVE PRIVATE KEY; --remove ephemeral private key
GO
--users only need permissions on directly invoked module
GRANT EXECUTE ON dbo.MyTestFunction TO YourUser;
GO
I can't find an answer to this. Problem is that I need to use master database and then I don't know how to specify that I am granting this select to a role in another database. When using "use master" it doesn't work because the principal is in another database and you can't add e.g. Database.dbo.role prefixes to principles. How do I do that? Even granting through SSMS UI doesn't work.
I need this: GRANT SELECT ON Syf.sys.server_principals to Syf.dbo.usersys
What am I missing? Am I thinking about this in a wrong way?
Even when I try it with the user on master database and call "execute as user = 'user'" and then select from sys.server_principals it still return only a few records. I apparently don't understand how these permissions work, it's beyond my logic. It seems there are some other objects that I need to grant permissions for.
I need to use "with execute as 'privilegedUser'", when I do that then we are in user context of that SP database and that user can't have permission to access sys.server_principals.? I need this because that SP deletes user and login if login with the same name exists. The reason I need to execute with the privileged user is because my database has multitenancy and every user is bound to one TenantId and when he or other user goes to delete the user, security policy complains that he has no right for that.
I found a way to do this, I have to grant select to sys.server_principals to guest user on master db, that gives guest some more privileges.
From the documentation on sys.server_principals, the needed permissions are:
Any login can see their own login name, the system logins, and the fixed server roles. To see other logins, requires ALTER ANY LOGIN, or a permission on the login. To see user-defined server roles, requires ALTER ANY SERVER ROLE, or membership in the role.
The visibility of the metadata in catalog views is limited to securables that a user either owns or on which the user has been granted some permission. For more information, see Metadata Visibility Configuration.
But all is not lost. We can use module signing to create a stored procedure that can allow you to do what you need to do.
use master;
create master key encryption by password = 'an unguessable password!'
alter master key add encryption by service master key
create certificate [CodeSigningCert]
with expiry_date = '2018-12-31',
subject = 'Code signing'
go
create login [CodeSigningLogin] from certificate [CodeSigningCert]
grant alter any login to [CodeSigningLogin]
go
SELECT 'CREATE CERTIFICATE ' + QUOTENAME([name])
+ ' AUTHORIZATION ' + USER_NAME([c].[principal_id])
+ ' FROM BINARY = ' + CONVERT(VARCHAR(MAX), CERTENCODED([c].[certificate_id]), 1)
+ ' WITH PRIVATE KEY (BINARY = '
+ CONVERT(VARCHAR(MAX), CERTPRIVATEKEY([c].[certificate_id], 'f00bar!23'), 1)
+ ', DECRYPTION BY PASSWORD = ''f00bar!23'')'
FROM [sys].[certificates] AS [c]
WHERE [name] = 'CodeSigningCert'
use tempdb
go
create master key encryption by password = 'foobar!23'
-- c/p the create certificate code generated above here
-- to create the same certificate in tempdb
create user CodeSigningUser from certificate CodeSigningCert
go
create login [foobar] with password = 'foobar!23'
create user [foobar]
go
create procedure dbo.listServerPrincipals
as
begin
select *
from sys.server_principals
end
go
grant execute on dbo.listServerPrincipals to foobar
go
execute as login = 'foobar'
go
exec dbo.listServerPrincipals
revert
go
add signature to dbo.listServerPrincipals by certificate [CodeSigningCert]
go
execute as login = 'foobar'
go
exec dbo.listServerPrincipals
revert
go
It seems like a lot, but in essence you're doing the following:
creating a certificate in master
creating a login from that certificate
creating that same certificate in your user database (I used tempdb as a standin here)
create a user for that certificate
create a login/user to represent your application user
create a procedure that does the select
try to execute it as the app login. it "works", but looks no different than if you'd done the select yourself
add a signature to the procedure
try to execute the procedure again. this time, it should return all the data
I've figured out a solution where I don't need to use "with execute as owner" in this first procedure, but in the second one that this first one calls. In the first one, I can select everything I need from sys tables and pass the info to a second one that has "with execute as owner" which is in the schema forbidden to a user.
Even better solution:
alter trigger [dbo].[AfterInsertUpdateTenant_Korisnici]
on [dbo].[Korisnici]
with execute as owner
for insert
as
execute as user = original_login();
declare #TenantId int = dbo.GetCurrentTenantId();
revert;
update dbo.Korisnici
set TenantId = #TenantId
from Inserted i
where dbo.Korisnici.Id = i.Id;
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