MSSQL: Limited account that's only allowed to read certain views? - sql-server

How do I create a MS SQL server user that only allowed to read certain views of a particular database?

Here's a script that creates a new user and gives him select only permissions on a specific view.
USE [master]
GO
CREATE LOGIN [LimitedUser] WITH PASSWORD=N'testPass',
DEFAULT_DATABASE=[master],
CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
GO
USE [TestDB]
GO
CREATE USER [LimitedUser] FOR LOGIN [LimitedUser]
GO
use [TestDB]
GO
GRANT SELECT ON [dbo].[myView] TO [LimitedUser]
GO
Edit
Instead of doing this for a specific user you might want to consider using Roles instead.
USE [TestDB]
GO
CREATE ROLE [LimitedRole]
GO
GRANT SELECT ON [dbo].[TestView] TO [LimitedRole]
GO
EXEC sp_addrolemember N'LimitedRole', N'LimitedUser'
GO
This way if you have multiple users for example in a Windows Authenitcation Mode you might have many users, all can be granted access to this role. This way as you add / remove views you don't have to touch every user.

The trick to doing this is to not give any explicit permissions to the Public role. Every user is irrevocably a member of that role so there is no way to prevent any user of the DB from having any rights you give to Public.
Aside from that, you just add the user to the appropriate DB and only give them rights to the objects you are interested in.

Related

SQL query to map login user to a particular database

I want to map login user (i.e. TestUser) to already created database (i.e. JIRADB), but after executing below query no user is added in JIRADB.
Refer the image link provided, I want JIRADB to be checked after execution of the query.
Can someone help me with the exact query to achieve this task?
Here is the code, which I currently tried:-
USE [JIRADB]
GO
CREATE LOGIN TestUser WITH PASSWORD="sauser123', DEFAULT_DATABASE=[JIRADB], CHECK_EXPIRATION=OFF, CHECK_POLICY=ON
GO
Just creating a login isn't enough, that login needs a user in the database as well that is mapped to the login.
USE [master]
GO
CREATE LOGIN TestUser WITH PASSWORD="sauser123', DEFAULT_DATABASE=[JIRADB], CHECK_EXPIRATION=OFF, CHECK_POLICY=ON
GO
USE [JIRADB]
GO
CREATE USER [TestUser] FOR LOGIN [TestUser]
GO
--Optional, add the user to database roles if required
ALTER ROLE db_datareader ADD MEMBER [TestUser]
GO
You will notice I also have an alter role statement in there as well, as if you just create a user in a database, it will just be a member of the public role, if you need any other permissions you must either add the user to a database role, or explicitly assign permissions to them.

SQL Server : can you limit access to only one table

I think the answer is no but I'm looking to give someone access to a SQL Server database but I only really want them to have access to one table.
It's easy enough to limit someone to only access one database but have no idea if I can limit to a single table.
My thoughts were to create another database with a synonym to the other table and then limit the access to that database but I wondered if someone could think of a better way.
I'm also not convinced that it will work as I think there will be a conflict of permissions.
Yes.
exec sp_msforeachtable "DENY SELECT ON ? TO [username];"
GO
GRANT SELECT ON [schemaName].[tableName] to [username]
Go
While that works, you would probably be better off managing permissions using roles and AD groups.
The problem with looping through all tables and denying access would be if you add a new table.
The important thing is to not give the user 'db_datareader' access to the whole database. Using the UI you can use the User Mapping tab under the login, you can create the user with 'public' access only. Then you can go to the database and grant that user SELECT access to the particular table (by clicking the oddly named "Search" button under Securables tab).
This approach would work with script also of course.
GRANT SELECT ON [SchemaName].[TableName] to [UserName]
Certainly. GRANT the permissions you want.
When you give a user access to a database, look at the roles they are assigned and what rights those roles have.
The problem is that people generally grant too broad permissions in the beginning.
It is possible and quite easy. The following code works on my SQL 2019:
USE [master]
GO
-- Create test login deny rights on server layer
IF NOT EXISTS (SELECT NULL FROM sys.server_principals WHERE [name] = 'UserRightTest')
CREATE LOGIN [UserRightTest] WITH PASSWORD=N'abc1234$', DEFAULT_DATABASE=[master], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF;
GO
--DENY VIEW ANY DATABASE TO [UserRightTest]; -- optional, depends on how the login access the table
DENY VIEW SERVER STATE TO [UserRightTest];
GO
-- Grant only permissions to two tables
USE [MyTestDb]
GO
IF NOT EXISTS (SELECT NULL FROM sys.database_principals WHERE [type] = 'S' AND [name] = N'UserRightTest')
CREATE USER [UserRightTest] FOR LOGIN [UserRightTest] WITH DEFAULT_SCHEMA = [dbo];
GO
GRANT SELECT ON OBJECT::[dbo].[TestParentTable] TO [UserRightTest];
GRANT SELECT,INSERT,UPDATE,DELETE ON OBJECT::[dbo].[TestChildTable] TO [UserRightTest];
GO
Sure you can. After creating the user and giving them access to the database, grant only select access (or whatever level they need) to that table.
A better approach would be to create a separate schema, create a proc in that schema. Then allow the user to EXEC that proc. That's it. You could create a view in that schema and that may be more of what you're after.

The EXECUTE permission was denied on the object 'xxxxxxx', database 'zzzzzzz', schema 'dbo'

I'm having problems executing a function.
Here's what I did:
Create a function using SQL Server Management Studio. It was successfully created.
I then tried executing the newly created function and here's what I get:
The EXECUTE permission was denied on
the object 'xxxxxxx', database
'zzzzzzz', schema 'dbo'.
Sounds like you need to grant the execute permission to the user (or a group that they a part of) for the stored procedure in question.
For example, you could grant access thus:
USE zzzzzzz;
GRANT EXEC ON dbo.xxxxxxx TO PUBLIC
Best solution that i found is create a new database role i.e.
CREATE ROLE db_executor;
and then grant that role exec permission.
GRANT EXECUTE TO db_executor;
Now when you go to the properties of the user and go to User Mapping and select the database where you have added new role,now new role will be visible in the Database role membership for: section
For more detail read full article
In SQL Server Management Studio, go to security->schema->dbo:
Double-click dbo, select the Permissions page, then click the "View database permissions" link in blue:
Select the user for whom you want to change permissions, and look for the "Execute" permission under the "explicit" tab:
Choose the appropriate permission by checking the appropriate box.
you need to run something like this
GRANT Execute ON [dbo].fnc_whatEver TO [domain\user]
This will work if you are trying to Grant permission to Users or roles.
Using Microsoft SQL Server Management Studio:
Go to: Databases
Right click on dbo.my_database
Choose: Properties
On the left side panel, click on: Permissions
Select the User or Role and in the Name Panel
Find Execute in in permissions and checkmark: Grant,With Grant, or Deny
Giving such permission can be dangerous, especially if your web application uses that same username.
Now the web user (and the whole world wide web) also has the permission to create and drop objects within your database. Think SQL Injection!
I recommend granting Execute privileges only to the specific user on the given object as follows:
grant execute on storedProcedureNameNoquotes to myusernameNoquotes
Now the user myusernameNoquotes can execute procedure storedProcedureNameNoquotes without other unnecessary permissions to your valuable data.
You don't have the right to execute it, although you have enough permissions to create it.
For more information, see GRANT Object Permissions (Transact-SQL)
If you have issues like the question ask above regarding the exception thrown when the solution is executed, the problem is permission, not properly granted to the users of that group to access the database/stored procedure. All you need do is to do something like what i have below, replacing mine with your database name, stored procedures (function)and the type of permission or role or who you are granting the access to.
USE [StableEmployee]
GO
GRANT EXEC ON dbo.GetAllEmployees TO PUBLIC
/****** Object: StoredProcedure [dbo].[GetAllEmployees] Script Date: 01/27/2016 16:27:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[GetAllEmployees]
as
Begin
Select EmployeeId, Name, Gender, City, DepartmentId
From tblEmployee
End
here is how to give permission for one user not public,
Direct Query:
Use MyDatabase
Grant execute on [dbo].[My-procedures-name] to [IIS APPPOOL\my-iis-pool]
Go
You can give everybody execute permission:
GRANT Execute on [dbo].your_object to [public]
"Public" is the default database role that all users are a member of.
If you make this user especial for a specific database, then maybe you do not set it as db_owner in "user mapping" of properties
I have faced the same problem and I solved as give db_owner permission too to the Database user.
The general answer is to grant execute permission as explained above. But that doesn't work if the schema owner of SP is different to underlying objects.
Check schema owners by:
select name, USER_NAME(s.principal_id) AS Schema_Owner from sys.schemas s
To change the owner of an schema you can:
ALTER AUTHORIZATION ON SCHEMA::YOUR_SCHEMA TO YOUR_USER;
Examples:
ALTER AUTHORIZATION ON SCHEMA::Claim TO dbo
ALTER AUTHORIZATION ON SCHEMA::datix TO user1;
Finally if within your SP you are truncating a table or changing structure you may want to add WITH EXECUTE AS OWNER in your SP:
ALTER procedure [myProcedure]
WITH EXECUTE AS OWNER
as
truncate table etl.temp
If you only need to grant a single function then (only db admin can do it):
Open Management studio
Find function/procedure you want to grant in Object Eplorer (dbname-Programmability-[Functions/Stored Procedures]-...)
Right click on function or procedure name and open Properties
In Properties select Permissions, add user (or schema) you want and Grant him Execute permission.
I believe this is most secure way how to do it because you only grant to user execution of this function. Nothing else!
I think you have to select the object you want to grant access to, then right-click, and select properties. Select permission on the modal window that will be displayed then click on Search, on the newly revealed window, select browse, select the user you want to grant access and click on ok. it will display for you a list of permission and the grant status, and then you can choose to grant or deny
This shows that you don't have access to perform any action on the specified database table. To enable this, Go to Security -> Schema and check.
you'd better off modifying server roles, which was designed for security privileges. add sysadmin server role to your user. for better security you may have your custom server roles. but this approach will give you what you want for now.
Object Explorer -> Server -> Security -> Logins
Right click on your desired user
Go to Server Roles on left hand side
Make sure sysadmin is checked
Hit OK and restart your SQL server
Good luck

How to grant permissions to developers to grant permissions to users?

Is there a way I can give developers permission to grant a user permissions over objects without giving them the option to create users or functions?
I'm trying to limit developers permissions, I recently found out that developers had db_owner permissions in dev and prod environments! So I'm doing my best to stop this madness.
Any good article about this matter?
You can make them members of the "db_securityadmin" database role
As said, if someone could hand out permissions, they could hand out permissions to themselves (or a dummy account). I'm not sure if there is a trick in SQL Server to provide "give user permissions less then me".
The way I would do it is with stored procedures.
Create a stored procedure that gives a specified user a specific right or set of rights (those rights are the ones that regular users are allowed to have). Then give the developers execute access to this stored procedure. In effect you use stored procedures to create a limited version of GRANT, while keeping the full GRANT command to yourself.
If someone can give someone else permissions, he can also give himself the permission to do what he wants. So what is this good for? Probably I don't understand your situation.
Owners of objects can grant permissions on those objects. Provided your developers don't need to grant things like CREATE TABLE rights, you might be able to give them ownership of the objects that you want them to grant permission on.
As Stefan said, giving them grant permissions would effectively give them all permissions, since if they want to do something all they have to do is grant themselves the permissions to do it.
Rather than considering the developers the enemy, though, you may want to consider giving the developers a second user account that's used to administer the database. It's pretty common not to give developers ANY permissions to production, at least on their development account.
Setting permission on objects like stored procedures can be accomplished with "GRANT EXECUTE ON . to ;
However, you may also want to grant security rights at both the login and user level. You will want to determine and grant ONLY the necessary rights for the objects that require access (such as execution). Consider use of the "EXECUTE AS" capability which enables impersonation of another user to validate permissions that are required to execute the code WITHOUT having to grant all of the necessary rights to all of the underlying objects (e.g. tables). The EXECUTE AS can be added to stored procs, functions, triggers, etc.
Add to the code as follows right within the Stored Procedure: CREATE PROCEDURE dbo.MyProcedure WITH EXECUTE AS OWNER
In this case you are impersonating the owner of the module being called. You can also impersonate SELF, OR the user creating or altering the module OR... imperonate CALLER , which will enable to module to take on the permissionsof the current user, OR... impersonate OWNER, which will take on the permission of the owner of the procedure being called OR... impersonate 'user_name', which will impersonate a specific user OR... impersonate 'login_name' with will impersonate a specific login.
MOST of the time, you will only need to grant EXECUTE rights to stored procs and then rights are granted to all objects referenced within the stored proc.
In this way, you DO NO need to give implicit rights (example: to update data or call additional procs). Ownership chaining handles this for you. This is especially helpful for dynamic sql or if you need to create elevated security tasks such as CREATE TABLE. EXECUTE AS is a handy tool to consider for these.
This example may help clarify all of this:
Create a user called NoPrivUser with public access to a database (e.g. dbadb)
USE [master] GO CREATE LOGIN [NoPrivUser] WITH PASSWORD=N'ABC5%', DEFAULT_DATABASE=[dbadb], CHECK_EXPIRATION=ON, CHECK_POLICY=ON GO USE [DBAdb] GO CREATE USER [NoPrivUser] FOR LOGIN [NoPrivUser] GO
NOTE: CREATOR OR OWNER OF THIS PROCEDURE WILL REQUIRE CREATE TABLE RIGHTS within the target database.
use DBAdb go CREATE PROCEDURE dbo.MyProcedure WITH EXECUTE AS OWNER AS IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].MyTable') AND type in (N'U')) CREATE TABLE MyTable (PKid int, column1 char(10)) INSERT INTO MyTable VALUES (1,'ABCDEF')
GO
GRANT EXEC ON dbo.MyProcedure TO NoPrivUser; GO
-- Now log into your database server as NoPrivUser and run the following.
use dbadb go
EXEC dbo.MyProcedure
(1 row(s) affected)
Now try to select from the new table while logged on as NoPrivuser.
You will get the following:
select * from MyTable go
Msg 229, Level 14, State 5, Line 1 The SELECT permission was denied on the object 'MyTable', database 'DBAdb', schema 'dbo'.
That is expected since you only ran the procedure under the security context of Owner while logged on as NoPrivUser.
NoPrivUser as no rights to actually read the table. Just to execute the procedure which creates and inserts the rows.
With the EXECUTE AS clause the stored procedure is run under the context of the object owner. This code successfully creates dbo.MyTable and rows are inserted successfully. In this example, the user "NoPrivUser" has absolutey no granted rights to modify the table, or read or modify any of the data in this table.
It only takes on the rights needed to complete this specific task coded WITHIN the context of this procedure.
This method of creating stored procedures that can perform tasks that require elevated security rights without permanently assigning those rights come be very useful.
I've found that the most dangerous aspect of the db_owner role is that if you issue a deny on a permissions, then the members of the role can grant it back to themselves. I've just started reading about this and I'm testing this
Create role db_ControlDatabase
grant control to db_ControlDatabase
deny backup database to db_ControleDatabase
alter role db_ControlDatabase add member TestUser
So far, I've found that the subject TestUser has permissions without being able to add or remove members of the fixed database roles. You should be able to deny whatever you need at this point like backup certificate, backup master key, etc.
Here is a list of permissions that can be denied or granted:

Permissions required for 'CREATE USER' in SQL Server 2005?

I am trying to create a SQL server login and database user from within my application, along with a custom application user row. I want these users to be able to create other users - i.e. the application will control who can/can't create users but I need all users to have permissions for creating SQL server logins and database users.
I have got the server login permissions working - i.e. an existing user/login can create a new login - by adding the logins to the 'securityadmin' server role - which grants the 'ALTER ANY LOGIN' privilege.
I tried to do the same with the database users - adding them to the 'db_accessadmin' database role - which supposedly grants the ALTER ANY USER privilege, which is required for CREATE USER.
However any time I try to create a new database user using a user with the above privileges I get a permissions exception.
I have tried manually granting the ALTER ANY USER permission to a particular user (GRANT ALTER ANY USER TO demouser) but this doesn't work either.
Technically, yes. Whether it's right or wrong... no comment.
Anyway, database security is split into 2 functions:
db_accessadmin to manage users (or "ALTER ANY USER" permission as you mentioned)
db_securityadmin allows you to manage roles memberships and object permissions (or "ALTER ANY ROLE permission)
This is mentioned for sp_addrolemember.
You are actually changing the role, not the user, by running sp_addrolemember so "ALTER ANY ROLE" is enough without having full db_owner rights.
My bad - I have found the issue - it was not the CREATE USER that was failing, but a subsequent call to 'sp_addrolemember'. This requires further permissions that I wasn't assigning.
In particular I needed to add my users to the db_owner database role in order to allow them to assign other/new users to fixed database roles.
Is there a cleaner way to allow me to achieve what I am trying to do here - i.e. create users that are allowed to create other users?
This seems very dangerous, easily becoming a security nightmare. Not knowing anything about why you think this is the best solution to accomplish your objective I can't really tell you not to do it this way, but wow!! - I would think long and hard about whether this really is necessary. The spider-webbing of users just seems like it could quickly be impossible to manage from a DBA perspective.
Would you not be able to just have one SQL account that has the permissions to add users, and the application uses that every time to add new users? Those users then would not need the ability to add other users. Maybe this won't work for your specific objective, but surely there is some other way.
But having said all that ... no, there is not really a cleaner way. The user would have to be assigned to the correct roles in order to have the ability to later add other users.
/*
TOPIC: create a login ,who can add other logins to databases (securityadmin server role)
*/
USE MASTER
GO
Create login securityTestLogin with password = '##somepassword123'
-----add this to server , this is server level security role -------
EXEC master..sp_addsrvrolemember #loginame = N'securityTestLogin', #rolename = N'securityadmin'
--- first this login should be a user in database where we want to give other users access
USE HTDBA
GO
Create user securityTestLogin for login securityTestLogin
EXEC sp_addrolemember N'db_accessadmin', N'securityTestLogin'
-- depends on your requriemtnt you might also want this permission too
--EXEC sp_addrolemember N'db_securityadmin', N'securityTestLogin'
GO
------ Now we think about adding other users to different database roles -------------
/*
There is one gottcha , db_securityadmin role cannot add users to the fixed database roles ,only
db_owner can perform this action , but for security we don't want to give this permission .
so we need a work around
Create a role with required permission and then add users to that role.
*/
--Create user defined database role Readers
EXEC sp_addrole DBUser
-- Add this role to fixeddbroles to get database level permission
EXEC sp_addrolemember db_datareader, DBUser
EXEC sp_addrolemember db_datawriter, DBUser
GO
--------READY TO TEST --------
------ we are using this sample login for test
use master
Go
Create login testlogin1 with password='##somepassword123'
use HTDBA
go
Create user testlogin1 for login testlogin1
--- now add this user to user created DBUser role .
EXEC sp_addrolemember DBUser, testlogin1
A very good article on SQL permissions:
http://www.sqlservercentral.com/articles/Security/sqlserversecurityfixeddatabaseroles/1231/

Resources