Was wanting to add full access for a developer to a database.
I wanted them to be able to have full control over it...including deleting it if they wanted.
Somehow I stumbled upon two ways. Are these the right ways??
What's the difference of between access/permissions between the both commands?
What is the correct command to accomplish what I want?
Thanks.
Command 1
USE [testdb1]
GO
ALTER USER [john] WITH DEFAULT_SCHEMA=[dbo]
GO
Command 2
USE [testdb1]
GO
EXEC sp_addrolemember N'db_owner', N'john'
GO
According to the latest sp_addrolemember documentation, sp_addrolemember should be avoided and ALTER ROLE should be used instead.
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. Use ALTER ROLE instead.
There is no difference between the two as of SQL Server 2012.
alter role [RoleName] add member [MemberName];
is equivalent to
exec sp_addrolemember N'RoleName', N'MemberName';
References:
https://msdn.microsoft.com/en-us/library/ms189775.aspx
https://msdn.microsoft.com/en-us/library/ms187750.aspx
MSDN is a great source for answering that:
sp_addrolemember
Adds a database user, database role, Windows login, or Windows group
to a database role in the current database.
ALTER USER
Renames a database user or changes its default schema.
Note also the syntax:
sp_addrolemember [ #rolename = ] 'role',
[ #membername = ] 'security_account'
-- SQL Server Syntax
ALTER USER userName
WITH <set_item> [ ,...n ]
[;]
<set_item> ::=
NAME = newUserName
| DEFAULT_SCHEMA = { schemaName | NULL }
| LOGIN = loginName
| PASSWORD = 'password' [ OLD_PASSWORD = 'oldpassword' ]
| DEFAULT_LANGUAGE = { NONE | <lcid> | <language name> | <language alias> }
| ALLOW_ENCRYPTED_VALUE_MODIFICATIONS = [ ON | OFF ]
In other words, using sp_addrolemember, you could only add database user, database role, Windows login, or Windows group in the current database.
But using ALTER USER, you could alter its name, its default schema, its login name, its password, etc... which certain is unable to be done by using sp_addrolemember.
Check the two MSDN links. They are great source for info using SQL Server
As for your case, you probably want to use sp_addrolemember, provided that you already have a role which could give the user the access that they need (most probably db_owner).
USE [testdb1]
GO
EXEC sp_addrolemember N'db_owner', N'john'
GO
When you alter default schema of a user, it does not mean that they get new role - but they get new default schema, and the accessibility will depend on the security rules in the new schema for the existing user role. It could give you what you want, depends on the security rules for the user in the default schema it has.
Related
So, Im using Informix DB engine to create my database. I have noticed something peculiar I cannot find information about in the official IBM page.
If you check the definition of my table, there is a line at the end saying :
revoke all on "gabriel.barrios".proveedores from "public" as "gabriel.barrios";
I did not write that, I simply defined the table attributes. But it seems as the engine itself is adding that.
Is this the case?
And if it is, how can I cahnge this default behaviour.
Additionally, could someone clarify ths line's output :
{ TABLE "gabriel.barrios".proveedores row size = 110 number of columns = 4 index size = 9 }
[gabriel.barrios#informix1 ~]$ dbschema -d practico_matias_barrios -t Proveedores
DBSCHEMA Schema Utility INFORMIX-SQL Version 11.70.UC8W1
{ TABLE "gabriel.barrios".proveedores row size = 110 number of columns = 4 index size = 9 }
create table "gabriel.barrios".proveedores
(
id serial not null ,
nombre varchar(50) not null constraint "gabriel.barrios".proveedor_nombre_vacio,
situacion integer not null constraint "gabriel.barrios".proveedor_situacion_vacio,
ciudad varchar(50) not null constraint "gabriel.barrios".proveedor_ciudad_vacio,
primary key (id) constraint "gabriel.barrios".proveedor_clave_primaria
);
revoke all on "gabriel.barrios".proveedores from "public" as "gabriel.barrios";
Informix default behavior is to grant privileges to the PUBLIC role.
As per the documentation (Table-level privileges) :
In an ANSI-compliant database, only the table owner has any
privileges. In other databases, the database server, as part of
creating a table, automatically grants to PUBLIC all table privileges
except Alter and References, unless the NODEFDAC environment variable
has been set to 'yes' to withhold all table privileges from PUBLIC.
When you allow the database server to automatically grant all table
privileges to PUBLIC, a newly created table is accessible to any user
with the Connect privilege. If this is not what you want (if users
exist with the Connect privilege who should not be able to access this
table), you must revoke all privileges on the table from PUBLIC after
you create the table.
What your are seeing is dbschema always revoking privileges from PUBLIC on the create table output and then adding them back on the privileges output.
$ dbschema -d mydatabase -t default_privileges
DBSCHEMA Schema Utility INFORMIX-SQL Version 12.10.FC12
{ TABLE "myuser".default_privileges row size = 4 number of columns = 1 index size = 0 }
create table "myuser".default_privileges
(
id integer
);
revoke all on "myuser".default_privileges from "public" as "myuser";
Using dbschema privileges output and filtering by table default_privileges :
$ dbschema -d mydatabase -p all | grep default_privileges
grant select on "myuser".default_privileges to "public" as "myuser";
grant update on "myuser".default_privileges to "public" as "myuser";
grant insert on "myuser".default_privileges to "public" as "myuser";
grant delete on "myuser".default_privileges to "public" as "myuser";
grant index on "myuser".default_privileges to "public" as "myuser";
I am executing a SQL script in SQL Server Management Studio 2018. In my script I need to specify a user (including the domain - unsure if I need the server name).
So I have created a user sam, set the user type to SQL user without login and set the users role to db_datareader and db_datawriter.
I then execute my script but it gives me the error: User or role 'MHT.sam' does not exist in this database.
But I am almost certain I have added this user to the database (see my images below to double check). Is my user and domain name format correct? What do you think I am doing wrong?
Here's my domain and server:
The error is pretty obvious.
In your screen shot in the object explorer you have a user called SAM, but for sp_AddRoleMember you are using MHT.SAM user.
Your sp_addrolemember should also have only Sam something like...
Exec sp_addrolemember N'RunStoredProc' , N'Sam'
GO
Also to double check what your user type is what login it is mapped to and what really is going on, use the following query.
SELECT
d.name AS User_Name
, d.type_desc AS User_Type
, d.default_schema_name AS User_default_schema_name
, d.create_date AS User_Created_Date
, s.name AS Login_name
, s.type_desc AS Login_LoginType
, s.is_disabled AS Login_is_disabled
, s.create_date AS Login_create_date
, s.default_database_name AS Login_default_database_name
, s.default_language_name AS Login_default_language_name
FROM sys.server_principals s
INNER JOIN sys.database_principals d on s.sid = d.sid
WHERE d.name = 'Sam'
I'm trying to learn Postgres and Ive made two basic tables and I can't join them together.
here is my list Of relations:
Schema | Name | Type | Owner
--------+--------------+----------+----------
public | login | table | postgres
public | login_id_seq | sequence | postgres
public | users | table | test
(3 rows)
When I use the command
SELECT * FROM users JOIN login ON users.name = login.name;
I get
ERROR: permission denied for relation login
I have no idea what to do or what I did wrong.
You should grant the SELECT permission to user test:
GRANT SELECT ON login TO test;
If if might allow test to modify login, you should grant other permissions as well:
GRANT SELECT, INSERT, UPDATE, DELETE ON login TO test;
You should execute these statements as database owner or as user postgres. In general, you can use
psql -Upostgres -dtest
if you're running this command on the same machine where the Postgres server is running.
You may also change the ownership of login to test:
ALTER TABLE login OWNER TO test;
ALTER SEQUENCE login_id_seq OWNER TO test;
But have to execute this as user postgres as well.
Edit: You can try to change the user with
SET ROLE 'postgres';
as suggested by #lat long.
So this is what I did to finally get it to work...I basically just went into the login properties on pgAdmin4, found the owner and switched it to test and ran:
SELECT * FROM users JOIN login ON users.name = login.name;
and finally got what I was looking for. Surprisingly a simple fix.
The "test" user doesn't have permission to login and use the related tables. Run the query with the "postgres" user:
SET ROLE 'postgres';
Then run your query.
I created a new superuser just so that this user can run COPY command.
Note that a non-superuser cannot run a copy command.
I need this user due to a backup application, and that application requires to run COPY command
But all the restrictions that I specified does not take effect (see below).
What is the difference between user postgres and a superuser?
And is there a better way to achieve what I want? I looked into a function with security definer as postgres ... that seems a lot of work for multiple tables.
DROP ROLE IF EXISTS mynewuser;
CREATE ROLE mynewuser PASSWORD 'somepassword' SUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT LOGIN;
-- ISSUE: the user can still CREATEDB, CREATEROLE
REVOKE UPDATE,DELETE,TRUNCATE ON ALL TABLES IN SCHEMA public, schema1, schema2, schema3 FROM mynewuser;
-- ISSUE: the user can still UPDATE, DELETE, TRUNCATE
REVOKE CREATE ON DATABASE ip2_sync_master FROM mynewuser;
-- ISSUE: the user can still create table;
You are describing a situation where a user can write files to the server where the database runs but is not a superuser. While not impossible, it's definitely abnormal. I would be very selective about who I allow to access my DB server.
That said, if this is the situation, I'd create a function to load the table (using copy), owned by the postgres user and grant the user rights to execute the function. You can pass the filename as a parameter.
If you want to get fancy, you can create a table of users and tables to define what users can upload to what tables and have the table name as a parameter also.
It's pretty outside of the norm, but it's an idea.
Here's a basic example:
CREATE OR REPLACE FUNCTION load_table(TABLENAME text, FILENAME text)
RETURNS character varying AS
$BODY$
DECLARE
can_upload integer;
BEGIN
select count (*)
into can_upload
from upload_permissions p
where p.user_name = current_user and p.table_name = TABLENAME;
if can_upload = 0 then
return 'Permission denied';
end if;
execute 'copy ' || TABLENAME ||
' from ''' || FILENAME || '''' ||
' csv';
return '';
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
COPY with option other than writing to STDOUT and reading from STDIN is only allowed for database superusers role since it allows reading or writing any file that the server has privileges to access.
\copy is a psql client command which serves the same functionality as COPY but is not server-sided, so only local files can be processed - meaning it invokes COPY but ... FROM STDIN / ... TO STDOUT, so that files on a server are not "touched".
You can not revoke specific rights from a superuser. I'm quoting docs on this one:
Docs: Access DB
Being a superuser means that you are not subject to access controls.
Docs: CREATE ROLE
"superuser", who can override all access restrictions within the database. Superuser status is dangerous and should be used only when really needed.
I create the database in Management Studio. Added a SQL authenticated user to the list of users for the DB.
I set up (granted) the permissions like so:
use DjangoDB;
grant select,insert,update,alter,delete,references to django;
select
a.*,
b.name
from sys.database_permissions a
inner join sys.database_principals b
on a.grantee_principal_id = b.principal_id
and b.name = 'django'
The output of this command is:
class class_desc major_id minor_id grantee_principal_id grantor_principal_id type permission_name state state_desc name
0 DATABASE 0 0 5 1 AL ALTER G GRANT django
0 DATABASE 0 0 5 1 CO CONNECT G GRANT django
0 DATABASE 0 0 5 1 DL DELETE G GRANT django
0 DATABASE 0 0 5 1 IN INSERT G GRANT django
0 DATABASE 0 0 5 1 RF REFERENCES G GRANT django
0 DATABASE 0 0 5 1 SL SELECT G GRANT django
0 DATABASE 0 0 5 1 UP UPDATE G GRANT django
So the user appears to have the permissions (especially select which it will later claim is not a permission this user has)
Then I run python manage.py syncdb
Syncing...
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
...
and I (sometimes) get an error like:
File "E:\python\cloudbox\.cloudbox\lib\site-packages\sqlserver_ado\dbapi.py", line 99, in standardErrorHandler
raise errorclass(errorvalue)
DatabaseError: (-2147352567, 'Exception occurred.', (0, u'Microsoft OLE DB Provider for SQL Server', u"User 'django' does not have permission to run DBCC checkconstraints for database 'DjangoDB'.", None, 0, -2147217900), None)
Command:
DBCC CHECKCONSTRAINTS
Parameters:
[]
When I look up this error, it says:
Requires membership in the sysadmin fixed server role or the db_owner fixed database role.
I can find a whole list of roles to put this user into, but none of them are sysadmin. Where is this role hidden?
If I immediately rerun syncdb without changing anything, I get a different error though:
sqlserver_ado.dbapi.DatabaseError: (-2147352567, 'Exception occurred.', (0, u'Microsoft OLE DB Provider for SQL Server', u"The SELECT permission was denied on the object 'django_content_type', database 'DjangoDB', schema 'dbo'.", None, 0, -2147217911), None)
Command:
SELECT [django_content_type].[id], [django_content_type].[name], [django_content_type].[app_label], [django_content_type].[model] FROM [django_content_type] WHERE ([django_content_type].[model] = ? AND [django_content_type].[app_label] = ? )
Parameters:
[Name: p0, Dir.: Input, Type: adBSTR, Size: 10, Value: "permission", Precision: 0, NumericScale: 0, Name: p1, Dir.: Input, Type: adBSTR, Size: 4, Value: "auth", Precision: 0, NumericScale: 0]
Now it says the user doesn't have the SELECT privilege? But above it shows it DOES have the select privilege?
Is there some magic to granting the select privilege?
So, now the plot thickens. I make the sql user 'django' OWN the database. Now, everything will work, everything creates, no errors, south migration works.....
But I don't want my webserver user being the "owner" of the db. I want it to be able to do things like select,insert,update,alter,delete,references. But it seems like I can't just give it a limited set of permissions so it can fulfill that role. This seems a lot like running XP as administrator, something that does NOT make sense.
What am I doing wrong on permissions? Why does the webserver db user have to OWN this db?
Some Answers:
1) sysadmin is a Server Role, and not a database role like db_owner. It is much more powerful than making your user the database owner, so you definitely do not want to give it out.
2) For reasons that are something of a mystery, object-access permissions effectively must be granted to both the database (DjangoDB) and the schema (dbo). You already did the database, now you have to do the same for the schema. Here is what these commands might be in T-SQL:
GRANT DELETE ON SCHEMA::[dbo] TO [django]
GRANT EXECUTE ON SCHEMA::[dbo] TO [django]
GRANT INSERT ON SCHEMA::[dbo] TO [django]
GRANT REFERENCES ON SCHEMA::[dbo] TO [django]
GRANT SELECT ON SCHEMA::[dbo] TO [django]
GRANT UPDATE ON SCHEMA::[dbo] TO [django]
GRANT VIEW DEFINITION ON SCHEMA::[dbo] TO [django]
3) As for DBCC, it is a very powerful utility command, consequently, it requires powerful permissions. You may be able to grant your user the db_owner role instead of making them the owner of the database, but really that's not much better. Ideally, either your syncdb should only be executed by an admin instead of your app's users, or you should make a stored procedure to do the DBCC authorizing the proc with EXECUTE As OWNER, then authorize the user to that stored proc (already done if they are authorized to the schema, as above), and finally have syncdb changed to call that procedure instead of doing the DBCC directly.
sysadm is a server role.
The second error is occurring against a database called Amegy
You should not use the same user for both deployments and running the application code. They are different roles with different permission requirements.
Django's syncdb command requires the ability to enable/disable constraints and is part of its database API.