Cannot alter the server role 'bulkadmin' in side SP - sql-server

i have application and sql server 2012 user ( i need to keep him with minimum permission)
i need to perform bulk insert by my application .
so i need to grant and deny the bulk permission by using SP
when i try
Alter PROCEDURE grantRole #Grant bit
With Execute As Owner AS
if(#Grant=1)
ALTER SERVER ROLE [bulkadmin] ADD MEMBER [myUser]
else
ALTER SERVER ROLE [bulkadmin] DROP MEMBER [myUser]
GO
i get the error
Msg 15151, Level 16, State 1, Line 1
Cannot alter the server role 'bulkadmin', because it does not exist or you do not have permission.
note that :the SP 'grantRole' exec from my application by the connection of the user -which is the user need to grant/deny the role- with execute permission
but as developer i have the permission
how can i solved or is their another way

Related

Google Cloud SQL - Unable to change DB owner on restored database from .BAK file

I have restored a SQL Server 2019 database from a .BAK file to a Google Cloud SQL instance.
I can connect to the instance using Visual Studio SQL Connection. I issue the following command to check the database owner, which should be: mydb_adm
USE master;
SELECT suser_sname(owner_sid) AS 'DB Owner' FROM sys.databases WHERE name = 'mydb';
DB Owner
--------
sqlserver
The above is expected, as the restore was done while using the sqlserver account which is the default user created when the SQL instance is provisioned by Google Cloud (according to the docs).
So, I need to change the DB owner; I execute the following command:
USE mydb
EXEC sp_changedbowner 'mydb_adm'
The system displays the following error message:
Msg 15151, Level 16, State 1, Line 1
Cannot find the principal 'mydb_adm', because it does not exist or you do not have permission.
The same message is displayed for:
ALTER AUTHORIZATION ON DATABASE::mydb TO mydb_adm;
However, the "mydb_adm" principal DOES exist, i.e.:
SELECT name, sid FROM sys.server_principals WHERE name = 'mydb_adm';
name sid
---- ---
mydb_adm 0xD81398C7DB0D724BB2738A2EC59BB554
.. so it must be a permission problem with the sqlserver account. When I query the DB, it appears the "sqlserver" user does NOT have ALTER permissions, i.e.:
UserName Permission Type Permission State
-------- --------------- ----------------
sqlserver ALTER DENY
... So how can I change the database owner or issue any ALTER commands using the "sqlserver" account? (There seems to be no way to grant the ALTER permission to the sqlserver user).
Any help / advice would be appreciated.
Thank-you to #DanGuzman for providing a "work-around", i.e.: while connected to the SQL instance using the "sqlserver" user, the following commands were used:
USE mydb;
CREATE USER mydb_adm;
ALTER ROLE db_owner ADD member mydb_adm;
After some additional digging, I also found the following in the Google Cloud docs at https://cloud.google.com/sql/docs/sqlserver/users, which states:
Cloud SQL for SQL Server is a managed service, so it restricts access
to certain system stored procedures and tables that require advanced
privileges. In Cloud SQL, you cannot create or have access to users
with superuser permissions.
Note: The sysadmin role is not supported. Therefore, you cannot run
system stored procedures that require the sysadmin role. As one of
the many examples, you cannot run the sp_OADestroy stored procedure
because it requires the sysadmin role.
As well as the following from the SQL Server docs at https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-authorization-transact-sql?view=sql-server-ver15#remarks, which state:
Requirements for the person executing the ALTER AUTHORIZATION
statement: If you are not a member of the sysadmin fixed server role,
you must have at least TAKE OWNERSHIP permission on the database, and
must have IMPERSONATE permission on the new owner login.
hence, commands such as EXEC sp_changedbowner ... or ALTER AUTHORIZATION ON DATABASE:: ... will raise the error (Msg 15151, ... you do not have permission.)
Hope that helps anyone else that may run into this type of issue.

Can't add new user to Azure SQL Database

Trying to add a new SQL Server Authentication user to an Azure SQL Database instance. The script below is being used. I am logged in as the server admin.
But the script fails at the member role assignment. The login and user are created but I cannot login to the database server.
Script:
use [master]
CREATE LOGIN test WITH password='somethingsecure';
GO
CREATE USER test FROM LOGIN test;
GO
EXEC sp_addrolemember 'db_datareader', 'test';
EXEC sp_addrolemember 'db_datawriter', 'test';
However the above script fails with the following error:
Msg 15151, Level 16, State 1, Line 6
Cannot alter the role 'db_datareader', because it does not exist or you do not have permission.
Msg 15151, Level 16, State 1, Line 6
Cannot alter the role 'db_datawriter', because it does not exist or you do not have permission.
The issue is trying to add the User and Roles to the master database.
All that is needed is to create the Login against master and then create the User and assign Roles against the actual database in the Azure SQL Database server.
See modified script:
use [master]
CREATE LOGIN test WITH password='somethingsecure';
GO
use [your-database]
CREATE USER test FROM LOGIN test;
GO
EXEC sp_addrolemember 'db_datareader', 'test';
EXEC sp_addrolemember 'db_datawriter', 'test';
Note: If you want to create a User with access to the master database, this answer will not help.

DbCreator role can restore a database but not then access it in MSSQL Server

I am working on a tool which is having restore command to restore MSSQL databases. Till now tool was restoring the databases with sysadmin privileges. However, as per new requirement I want to minimize the access privilege for this command i.e restore should be done with dbcreator role instead of sysadmin. With dbcreator I am able to restore the databases, however this command also does some post-operation on the restored databases i.e. updating some value in table. Post-operation is failing with lack of access, since db_owner is required for this user. How to grant db_owner to current user(dbcreator) on the restored databases who is not sysadmin at run time so that my restore command succeeds along with post-operation.
One way to follow security principles of least privilege and role-based access controls is to encapsulate the T-SQL commands that require elevated permissions in a stored procedure. One can then sign the proc with a certificate to confer additional permissions without granting those permissions directly to users. Only execute permissions on the signed stored procedure are required and authorized users are limited to the encapsulated functionality.
Below is an example script to create a stored procedure and DBRestore role using this technique. If your actual RESTORE command contains options that can't be parameterized (e.g. WITH MOVE file locations), you'll need to use dynamic SQL in the proc and take special care to ensure the values validated and/or obtained from a trusted source (e.g. configuration table instead of ad-hoc parameter value).
USE master
GO
--create certificate in master database
CREATE CERTIFICATE sysadmin_cert_login_cert
ENCRYPTION BY PASSWORD = '<cert-password>'
WITH SUBJECT = 'For sysadmin privileges';
GO
--create login from certificate
CREATE LOGIN sysadmin_cert_login FROM CERTIFICATE sysadmin_cert_login_cert;
--confer sysadmin permissions to certificate login
ALTER SERVER ROLE sysadmin
ADD MEMBER sysadmin_cert_login;
GO
--create role for restore user(s)
CREATE ROLE DBRestoreRole;
GO
--create restore proc in master database
CREATE PROC dbo.usp_RestoreDatabase
#DatabaseName sysname
, #BackupFilePath varchar(255)
AS
BEGIN TRY
RESTORE DATABASE #DatabaseName FROM DISK=#BackupFilePath WITH REPLACE;
--after restore, set database owner as desired
ALTER AUTHORIZATION ON DATABASE::RestoreTest TO sa;
--execute post restore DML
UPDATE RestoreTest.dbo.SomeTable
SET SomeColumn = 1;
END TRY
BEGIN CATCH
THROW;
END CATCH;
GO
--grant execute permission to DBRestoreRole
GRANT EXECUTE ON dbo.usp_RestoreDatabase TO DBRestoreRole;
--sign proc with sysadmin certificate
ADD SIGNATURE TO dbo.usp_RestoreDatabase BY CERTIFICATE sysadmin_cert_login_cert WITH PASSWORD='<cert-password>';
--optionally, remove ephemoral private key after signing
ALTER CERTIFICATE sysadmin_cert_login_cert REMOVE PRIVATE KEY;
GO
--create example DBRestoreRole login/user
CREATE LOGIN RestoreTestLogin WITH PASSWORD = '<login-password>';
CREATE USER RestoreTestLogin;
ALTER ROLE DBRestoreRole
ADD MEMBER RestoreTestLogin;
GO
--test execution
EXECUTE AS LOGIN = 'RestoreTestLogin';
GO
EXEC dbo.usp_RestoreDatabase
#DatabaseName = N'RestoreExample'
, #BackupFilePath = 'E:\BackupFiles\RestoreExample.bak';
GO
REVERT;
GO

Set RESTRICTED_USER on Azure SQL database

I'm trying to set Azure SQL database to RESTRICTED_USER mode and facing the odd error I was unable to figure out myself.
Msg 5011, Level 14, State 2, Line 1
User does not have permission to alter database 'YourDB', the database does not exist, or the database is not in a state that allows access checks.
According to the documentation membership in database db_owner role should be enough. User is also given ALTER DATABASE permission.
RESTRICTED_USER allows for only members of the db_owner fixed database
role and dbcreator and sysadmin fixed server roles to connect to the
database, but does not limit their number. All connections to the
database are disconnected in the timeframe specified by the
termination clause of the ALTER DATABASE statement. After the database
has transitioned to the RESTRICTED_USER state, connection attempts by
unqualified users are refused.
https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-database-transact-sql-set-options
What else is needed to make database RESTRICTED_USER?
Code to reproduce:
CREATE LOGIN YourLogin WITH PASSWORD = 'password'
GO
-- USE YourDB;
-- switch to YourDB here, Azure SQL does not support USE statement
CREATE USER YourUser
FOR LOGIN YourLogin
WITH DEFAULT_SCHEMA = dbo
GRANT ALTER TO YourDB
EXEC sp_addrolemember N'db_owner', N'YourUser'
Then, the following statement fails.
ALTER DATABASE YourDB SET RESTRICTED_USER;
I tried to Repro the issue and only sysadmin could change the database state to restricted_user.
Also you have mentioned that documentation states membership in database db_owner role should be enough
But documentation states ,the roles which can make connection to the database ,when database is set to restricted_user mode
RESTRICTED_USER allows for only members of the db_owner fixed database role and dbcreator and sysadmin fixed server roles to connect to the database, but does not limit their number
In summary ,users having above said roles will be able to connect to database ,when it is set to restricted user,it doesn't state,that dbmanager can change the state of database to restricted user

How to add an user to sysadmin role using ALTER ROLE?

'sa' user when executing the below script, the following error message is shown.
IF NOT EXISTS (SELECT LOGINNAME FROM MASTER.DBO.SYSLOGINS WHERE NAME = N'p_sys')
BEGIN
CREATE LOGIN [p_sys] WITH PASSWORD=N'test', DEFAULT_DATABASE=[master], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF;
ALTER ROLE sysadmin ADD MEMBER p_sys;
END
Msg 15151, Level 16, State 1, Line 4
Cannot alter the role 'sysadmin', because it does not exist or you do not have permission.
I do not want to use sp_addsrvrolemember because MS says it is deprecated.
Please help.
alter role is for database roles, but sysadmin is server role. Try alter server role instead:
ALTER SERVER ROLE server_role_name ADD MEMBER p_sys

Resources