GRANT SELECT ON sys.server_principals to usersys role. How? - sql-server

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;

Related

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
*/

Why a user with sysadmin permissions can't access msdb as an EXECUTE AS user?

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

"Execute as self" vs cross database views

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

How can someone see all rows in sys.sysprocesses and not be SA?

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.

Create User from a different DB in SQL Server

Is there any way I can create a user on a database from the master DB(or any other DB)
IF EXISTS (SELECT 1 FROM j_test.sys.database_principals WHERE name = N'test_user')
DROP USER j_test.[test_user]; --doesnt't work.
You either need to change the context to that database or dynamically go there:
EXEC j_test..sp_executesql N'DROP USER test_user;';
Logins are done at the server level, I usually create them from the [master] database. Just my convention.
Users are done at the database level. You need to have your context set to that database. The USE command allows you to switch between databases.
This snippet is from my blog that shows a hypothetical database [BSA] with a schema named [STAGE].
-- Which database to use.
USE [master]
GO
-- Delete existing login.
IF EXISTS (SELECT * FROM sys.server_principals WHERE name = N'BSA_ADMIN')
DROP LOGIN [BSA_ADMIN]
GO
-- Add new login.
CREATE LOGIN [BSA_ADMIN] WITH PASSWORD=N'M0a2r0c9h11$', DEFAULT_DATABASE=[BSA]
GO
-- Which database to use.
USE [BSA]
GO
-- Delete existing user.
IF EXISTS (SELECT * FROM sys.database_principals WHERE name = N'BSA_ADMIN')
DROP USER [BSA_ADMIN]
GO
-- Add new user.
CREATE USER [BSA_ADMIN] FOR LOGIN [BSA_ADMIN] WITH DEFAULT_SCHEMA=[STAGE]
GO

Resources