Create login with execute - sql

I am working on a project and I have access to SQL Server as external user with limited privileges.
When I want to create a login for example with this command, I get permission denied:
CREATE LOGIN [login] WITH PASSWORD=N'test', DEFAULT_DATABASE=[master],
DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF)
However when I try to create a login with this command I can make it and also I have privileges now to enable xp_cmd shell as well:
EXECUTE('EXECUTE(''CREATE LOGIN [test5] WITH PASSWORD=N''''test'''',
DEFAULT_DATABASE=[master], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF'') AT "hostname\domain"')
EXECUTE('EXECUTE(''ALTER SERVER ROLE [sysadmin] ADD MEMBER [test5]'')
EXECUTE('EXECUTE(''ALTER SERVER ROLE [db_owner] ADD MEMBER [test5]'')
Can someone please explain why is that?

EXECUTE('string sql statement') AT "hostname\domain" == the 'string sql statement' is a pass-through command executed at the linked server "hostname/domain".
Has someone created a loop-back linked server (a linked server that points to the sql instance itself)?
Linked servers have their own security configuration/settings. If the security of the linked server is configured (for any login) to be made under the security context of a privileged login(eg. sa) then exec('') at linkedserver will be executed with way more/elevated permissions (than expected). This is a major security issue/hole.
Check the security of the linked server and change accordingly (and do you really need a loopback linked server?)

Related

How to add username and password in sqllocaldb

I am going to start work on new Desktop application. There is I want to use light weight and standalone database so that I am going use SQL LocalDB but I want to add authentication. There I need username and password before accessing database but authentication not applied there please help me how can I do it.
If we cannot add username add password in SQL LocalDB then please suggest me any another database that will best for me and also I can use entity framework with that.
Thanks in advance
To add your new DB user to your MSSQLLocalDB you need to connect to it and execute this:
CREATE LOGIN your_user WITH PASSWORD = 'your_password';
CREATE USER your_user FOR LOGIN your_user;
EXEC sp_addrolemember 'db_owner', 'your_user'
Then you will be able to connect to MSSQLLocalDB database engine with SQL Server Authentication using these credentials.
Server name: (LocalDB)\MSSQLLocalDB
Authentication: SQL Server Authentication
User: your_user
Password: your_password
Or you can use instance pipe name instead of (LocalDB)\MSSQLLocalDB as a Server name (see below where to get it).
Initial connection to your local DB from SQL Server Management Studio (SSMS)
Initially to run the SQL command above you need to connect to your MSSQLLocalDB with Windows Authentication. You can do it in two ways (try the second if the first one won't work by default).
Using instance name
Server name: (LocalDB)\MSSQLLocalDB
Authentication: Windows Authentication
Using instance pipe name
From the command line go to C:\Program Files\Microsoft SQL Server\130\Tools\Binn\ (you might need to use other versions and replace \130\ with your folder name) and run SqlLocalDB.exe to find the local DB instances you have:
SqlLocalDB.exe i
Make sure you have MSSQLLocalDB listed. Then run this command to see the MSSQLLocalDB status (the first line) and start if it's stopped (the second line):
SqlLocalDB.exe i MSSQLLocalDB
SqlLocalDB.exe start MSSQLLocalDB
Then you can execute SqlLocalDB.exe i MSSQLLocalDB again to see the the instance pipe name. Something like this np:\\.\pipe\LOCALDB#D7900618\tsql\query
To connect in SSMS you need to enter:
Server name: np:\\.\pipe\LOCALDB#D7900618\tsql\query
Authentication: Windows Authentication
just want to add you need sysadmin role so you can create databases
using this code
ALTER SERVER ROLE sysadmin ADD MEMBER your_user;
GO
use this :
SqlConnection con = new SqlConnection("Server= localhost, Authentication=Windows Authentication, Database= employeedetails");
con.Open();
if you want sql server authentication than read this :
http://msdn.microsoft.com/en-us/library/ms162132.aspx

Sql Server grant permission for sp_grantdbaccess on a newly restored DB

I am unable to grant access to a newly restored database using sp_grantdbaccess. I am trying to do this via dynamic sql like below.
DECLARE #grant_access nvarchar(500)
SET #grant_access = 'EXEC ' + #new_db_name + '.dbo.sp_grantdbaccess ''IIS APPPOOL\myApp'''
EXEC sp_executesql #grant_access
I get the below error back trying to run this from a sproc. Any ideas on how I can grant permission for the app to call sp_grantdbaccess etc? I guess I am needing permission to give permission...
Error restore_backup restore_new_configDBThe server principal "IIS
APPPOOL\myApp" is not able to access the database "new_db_name" under
the current security context
Based on the error message it looks like you are trying to grant access to IIS APPPOOL\myApp using the security context IIS APPPOOL\myApp, but IIS APPPOOL\myApp doesn't have the access rights to the db to grant access rights to itself. I think this is akin to me trying to grant myself access to my neighbors house, but I don't have any authority to do so.
Depending on what type of security policies you are working under, I would either run the app pool under an account that has the greater privileges through integrated auth (but this might negate your need to grant privileges), or execute these SQL statements using a local SQL account with the necessary privileges to the database. In these cases, it would be like asking my neighbor (elevated access) to let me (IIS APPPOOL\myApp) in.
If you think it should work because IIS APPPOOL\myApp had access to the DB prior to being backed up, could this be a problem with IIS APPPOOL\myApp being an orphaned user? See http://msdn.microsoft.com/en-us/library/ms175475.aspx But with this case, you still might run into the above scenario trying to fix the orphaned user.

Taking ownership for SQL Server Management Studio

I'm new to SQL Server 2008. I just installed SQL Server Express. I'm having trouble creating a new database, and I think I don't have permission.
I login like this, please see this screenshot:
Then I tried to create a new database and I got this:
I tried to search for some solution and this what I've got:
http://blogs.msdn.com/b/sqlexpress/archive/2010/02/23/how-to-take-ownership-of-your-local-sql-server-2008-express.aspx
But I can't download the script and the page says:
An error occurred while processing your request.
Please help. Kind regards
I resolved my problem with the following steps:
Set the instance of the SQL Service to single-user mode:
Open SQL Server Configuration Manager. Double click SQL Server Services.
Stop all SQL Server services
Right click SQL service and click Properties, in the Advanced tab, look for 'Startup Parameters'
Insert '-m;' at the beginning of the Startup Parameters value
Start the SQL service
Open SQL Server Management Studio and login with Windows authentication, you can now add user or change password of different users.
Hope this helps!
Try logging in with the sa account and grant permissions to your Windows account.
If you do not know the sa password use sqlcmd and execute the following commands:
Use Master
Go
ALTER LOGIN [sa] WITH PASSWORD=N'NewPassword'
Go
Login with the sa account and GRANT permission to the account.
USE Master;
GRANT CREATE DATABASE TO Jommel;

SQL Agent Job - "Run As" drop down list is empty

Why is the "Run As" drop down list is always empty when I try to set up a SQL Agent Job? I am trying to set up some SQL Agent Jobs to run using a proxy account. I am a member of the SQLAgentUserRole, SQLAgentReaderRole, and SQLAgentOperatorRole. When I try to add a step to to the job, I select SQL Integration Services Package and the Run As drop down list is empty.
Anyone who is a sysadmin can view the proxy. Shouldn't I be able to use the proxy as a member of SQLAgentUserRole, SQLAgentReaderRole, and SQLAgentOperatorRole? What am I missing here?
(The proxy account is active to the subsystem: SQL Integration Service Packages and this is SQL Server 2008 R2)
EDIT -
MSDN: "Members of these database roles (SQLAgentUserRole, SQLAgentReaderRole, and SQLAgentOperatorRole) can view and execute jobs that they own, and create job steps that run as an existing proxy account." And this other article on fixed server roles mentions that access can be granted to proxies, but it does not mention how to do it: MSDN.
I found the answer to this. Users who are not sysadmin have to have access to the proxy account explicitly granted to their role or username:
To grant access to proxy accounts for non-sysadmins
In Object Explorer, expand a server.
Expand SQL Server Agent.
Expand Proxies, expand the subsystem node for the proxy, right-click the proxy you wish to modify, and click Properties.
On the General page, you can change the proxy account name, credential, or the subsystem it uses. On the Principals page, you can add or remove logins or roles to grant or remove access to the proxy account.
http://msdn.microsoft.com/en-us/library/ms187890(v=sql.100).aspx
When editing the job step - switch to "Advanced" tab on the left, don't use the dropdown on the main page.
Make sure the user is granted a role in the job database, even if he's a "sysadmin"
(the screenshot is for SSMS 17)
No, you shouldn't. Memebers of the roles you just mentioned can only create jobs that run as themselfes because they are non-administrative roles. If you want to run a job using antoher user, you'll need access to a proxy account. If I'm not mistaken, the only group that has access to create proxy accounts is sysadmin, so you'll need an admin to do that for you.
Members of the sysadmin role have permission to create job steps that
do not specify a proxy, but instead run as the SQL Server Agent
service account, which is the account that is used to start SQL Server
Agent.
Create credentials first then you will be able to add it under proxies level.
Once this is done then you can change from sql service agent to the credentials.
I had this problem with SQL Server 2017 and I wanted to not have to create a whole SSIS package just to run some SQL with the proxy user.
My solution was using the SQLCMD utility and run the SQL Agent Job step as the CmdExec type instead of running it as T-SQL.
Then you could have it run something like:
sqlcmd -S <ComputerName>\<InstanceName> -Q "SELECT * FROM AdventureWorks2012.Person.Person"
https://learn.microsoft.com/en-us/sql/ssms/scripting/sqlcmd-use-the-utility?view=sql-server-ver16

SQL Server Script to create a new user

I want to write a script to create a admin user ( with abcd password ) in SQL Server Express.
Also I want to assign this user admin full rights.
Based on your question, I think that you may be a bit confused about the difference between a User and a Login. A Login is an account on the SQL Server as a whole - someone who is able to log in to the server and who has a password. A User is a Login with access to a specific database.
Creating a Login is easy and must (obviously) be done before creating a User account for the login in a specific database:
CREATE LOGIN NewAdminName WITH PASSWORD = 'ABCD'
GO
Here is how you create a User with db_owner privileges using the Login you just declared:
Use YourDatabase;
GO
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'NewAdminName')
BEGIN
CREATE USER [NewAdminName] FOR LOGIN [NewAdminName]
EXEC sp_addrolemember N'db_owner', N'NewAdminName'
END;
GO
Now, Logins are a bit more fluid than I make it seem above. For example, a Login account is automatically created (in most SQL Server installations) for the Windows Administrator account when the database is installed. In most situations, I just use that when I am administering a database (it has all privileges).
However, if you are going to be accessing the SQL Server from an application, then you will want to set the server up for "Mixed Mode" (both Windows and SQL logins) and create a Login as shown above. You'll then "GRANT" priviliges to that SQL Login based on what is needed for your app. See here for more information.
UPDATE: Aaron points out the use of the sp_addsrvrolemember to assign a prepared role to your login account. This is a good idea - faster and easier than manually granting privileges. If you google it you'll see plenty of links. However, you must still understand the distinction between a login and a user.
Full admin rights for the whole server, or a specific database? I think the others answered for a database, but for the server:
USE [master];
GO
CREATE LOGIN MyNewAdminUser
WITH PASSWORD = N'abcd',
CHECK_POLICY = OFF,
CHECK_EXPIRATION = OFF;
GO
EXEC sp_addsrvrolemember
#loginame = N'MyNewAdminUser',
#rolename = N'sysadmin';
You may need to leave off the CHECK_ parameters depending on what version of SQL Server Express you are using (it is almost always useful to include this information in your question).
You can use:
CREATE LOGIN <login name> WITH PASSWORD = '<password>' ; GO
To create the login (See here for more details).
Then you may need to use:
CREATE USER user_name
To create the user associated with the login for the specific database you want to grant them access too.
(See here for details)
You can also use:
GRANT permission [ ,...n ] ON SCHEMA :: schema_name
To set up the permissions for the schema's that you assigned the users to.
(See here for details)
Two other commands you might find useful are ALTER USER and ALTER LOGIN.
If you want to create a generic script you can do it with an Execute statement with a Replace with your username and database name
Declare #userName as varchar(50);
Declare #defaultDataBaseName as varchar(50);
Declare #LoginCreationScript as varchar(max);
Declare #UserCreationScript as varchar(max);
Declare #TempUserCreationScript as varchar(max);
set #defaultDataBaseName = 'data1';
set #userName = 'domain\userName';
set #LoginCreationScript ='CREATE LOGIN [{userName}]
FROM WINDOWS
WITH DEFAULT_DATABASE ={dataBaseName}'
set #UserCreationScript ='
USE {dataBaseName}
CREATE User [{userName}] for LOGIN [{userName}];
EXEC sp_addrolemember ''db_datareader'', ''{userName}'';
EXEC sp_addrolemember ''db_datawriter'', ''{userName}'';
Grant Execute on Schema :: dbo TO [{userName}];'
/*Login creation*/
set #LoginCreationScript=Replace(Replace(#LoginCreationScript, '{userName}', #userName), '{dataBaseName}', #defaultDataBaseName)
set #UserCreationScript =Replace(#UserCreationScript, '{userName}', #userName)
Execute(#LoginCreationScript)
/*User creation and role assignment*/
set #TempUserCreationScript =Replace(#UserCreationScript, '{dataBaseName}', #defaultDataBaseName)
Execute(#TempUserCreationScript)
set #TempUserCreationScript =Replace(#UserCreationScript, '{dataBaseName}', 'db2')
Execute(#TempUserCreationScript)
set #TempUserCreationScript =Replace(#UserCreationScript, '{dataBaseName}', 'db3')
Execute(#TempUserCreationScript)
CREATE LOGIN AdminLOGIN WITH PASSWORD = 'pass'
GO
Use MyDatabase;
GO
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'AdminLOGIN')
BEGIN
CREATE USER [AdminLOGIN] FOR LOGIN [AdminLOGIN]
EXEC sp_addrolemember N'db_owner', N'AdminLOGIN'
EXEC master..sp_addsrvrolemember #loginame = N'adminlogin', #rolename = N'sysadmin'
END;
GO
this full help you for network using:
1- Right-click on SQL Server instance at root of Object Explorer, click on Properties
Select Security from the left pane.
2- Select the SQL Server and Windows Authentication mode radio button, and click OK.
3- Right-click on the SQL Server instance, select Restart (alternatively, open up Services and restart the SQL Server service).
4- Close sql server application and reopen it
5- open 'SQL Server Configuration Manager' and tcp enabled for network
6-Double-click the TCP/IP protocol, go to the IP Addresses tab and scroll down to the IPAll section.
7-Specify the 1433 in the TCP Port field (or another port if 1433 is used by another MSSQL Server) and press the OK
8-Open in Sql Server: Security And Login And Right Click on Login Name And Select Peroperties And Select Server Roles And
Checked The Sysadmin And Bulkadmin then Ok.
9-firewall: Open cmd as administrator and type:
netsh firewall set portopening protocol = TCP port = 1433 name = SQLPort mode = ENABLE scope = SUBNET profile = CURRENT
This past week I installed Microsoft SQL Server 2014 Developer Edition on my dev box, and immediately ran into a problem I had never seen before.
I’ve installed various versions of SQL Server countless times, and it is usually a painless procedure. Install the server, run the Management Console, it’s that simple. However, after completing this installation, when I tried to log in to the server using SSMS, I got an error like the one below:
SQL Server login error 18456
“Login failed for user… (Microsoft SQL Server, Error: 18456)”
I’m used to seeing this error if I typed the wrong password when logging in – but that’s only if I’m using mixed mode (Windows and SQL Authentication). In this case, the server was set up with Windows Authentication only, and the user account was my own. I’m still not sure why it didn’t add my user to the SYSADMIN role during setup; perhaps I missed a step and forgot to add it. At any rate, not all hope was lost.
The way to fix this, if you cannot log on with any other account to SQL Server, is to add your network login through a command line interface. For this to work, you need to be an Administrator on Windows for the PC that you’re logged onto.
Stop the MSSQL service.
Open a Command Prompt using Run As Administrator.
Change to the folder that holds the SQL Server EXE file; the default for SQL Server 2014 is “C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Binn”.
Run the following command: “sqlservr.exe –m”. This will start SQL Server in single-user mode.
While leaving this Command Prompt open, open another one, repeating steps 2 and 3.
In the second Command Prompt window, run “SQLCMD –S Server_Name\Instance_Name”
In this window, run the following lines, pressing Enter after each one:
1
CREATE LOGIN [domainName\loginName] FROM WINDOWS
2
GO
3
SP_ADDSRVROLEMEMBER 'LOGIN_NAME','SYSADMIN'
4
GO
Use CTRL+C to end both processes in the Command Prompt windows; you will be prompted to press Y to end the SQL Server process.
Restart the MSSQL service.
That’s it! You should now be able to log in using your network login.