New-SPConfigurationDatabase cannot connect to database/master unless I am logged into Windows desktop session - sql-server

This one is a doozy. Note, I'm using Ansible to automate, and that's part of the issue.
My ansible playbook fails with the following if I execute it remotely without being logged into the server:
"stderr": "New-SPConfigurationDatabase : Cannot connect to database master at SQL server at SERVERNAME.fqdn.
The database might not exist, or the current user does not have permission to connect to it.
I have a step in my playbook that confirm I am an AD user with the correct permissions on the database.
Furthermore, this playbook works if I happen to be logged into the server (target, where this is running) while the playbook runs. Note, there should be nothing linking the logged-in session to the ansible session, but it's like Active Directory (Kerberos?) only trusts this user when it's "really" logged in.
I did another quick test to see what SQL thought the user was trying to connect, as another task in the playbook:
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = tcp:SERVERNAME; Database = master; Authentication=Active Directory Integrated;Encrypt = False;TrustServerCertificate=True;"
$SqlConnection.open()
and when I'm logged into the desktop it connects without error. When I'm not logged into the desktop simultaneously, it reports fails with Login failed for user 'NT AUTHORITY\\ANONYMOUS "
Oh, and the ansible task is running with elevated privs; I don't understand why the SQL client seems to change it's mind which credentials to use based on whether the account is logged into with RDP.

Related

Windows password does not work for Powershell Credential Request

I am aware I can set up Powershell credentials Get-Credential for my own scripts. But when I use the following command Get a SQL Server instance on a computer in a PS terminal:
Get-SqlInstance -Credential laptop-ql9k5dk6\david -ServerInstance "laptop-ql9k5dk6\sqlexpress2"
I expect that I am going to be asked for my Windows password.
Here is my thinking:
Logging in to my SQL Server instance (laptop-ql9k5dk6\david) via MS SQL Server Management Studio (using Windows Authentication) uses my already logged on status. Otherwise I would need my Windows password.
Since my script is asking for a password for laptop-ql9k5dk6\david; I think it must be my Windows password?
So. Why does my Windows Password fail when my PowerShell one-liner (shown above) asks me for a password?
PowerShell credential request
Enter your credentials.
Password for user laptop-ql9k5dk6\david: **************
Get-SqlInstance: Failed to connect to server laptop-ql9k5dk6\sqlexpress2.
On MSSM I can also login via SQL Login but for that the username is different from the Windows Authentication user above.
Note: My current Windows password is good. I use it regularly without making mistakes/leaving CAPs on etc.
$role = "sql"
$user = read-host "user for $role"
$pwd = read-host "password:" -AsSecureString
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $user, $pwd
Get-SqlInstance -Credential $cred -ServerInstance "laptop-ql9k5dk6\sqlexpress2"
perhaps the cmdlet does not support Integrated Security=true;
Incorrect Password: One possibility is that you may be entering the wrong password. Double-check to ensure that you are entering the correct password for your Windows account.
Locked Account: If you have entered the wrong password too many times, your account may become locked. This can prevent you from accessing your account until it is unlocked. You can try unlocking your account by following the steps provided by your system administrator.
Expired Password: It is also possible that your Windows password has expired. In this case, you will need to reset your password before you can log in. You can reset your password by following the steps provided by your system administrator.
Credential Manager: If you are running your PowerShell script from a different machine or domain, your Windows credentials may not be recognized. In this case, you can try storing your credentials in the Windows Credential Manager. You can do this by running the cmdkey command in the command prompt or PowerShell.
System Permissions: If you are trying to run a PowerShell script that requires elevated privileges, you may need to run PowerShell as an administrator. Right-click on the PowerShell icon and select "Run as administrator".

Using SqlPackage to Extract DB results in "Login failed for user "someUser""

I am new to using SqlPackage.
I have a powershell command that looks something like
.\SqlPackage.exe /TargetFile:"C:\\Program Files\\Microsoft SQL Server\\150\\DAC\bin\\somefile.bacpac" /Action:extract /SourceServerName:"someServer" /SourceDatabaseName:"someDB" /SourceUser:"someUser" /SourcePassword:"somePassword" /DiagnosticsFile:"C:\\Program Files\\Microsoft SQL Server\\150\\DAC\\bin\\extract-log"
When I run this command I get the error
*** Error extracting database:Could not connect to database server.
Login failed for user "someUser"
I have checked the username and password and they are both correct. I used them to successfully login to SSMS. The user is the admistrator on the server, so should not be an issue with permissions I don't think.
I have followed the instructions to view the logs but under the server I do not have a Management tab. I do not understand why since I am the admin on the server.
Does anyone have any ideas on how I can find the source of the issue?
The reason for this error could be one of many. Without the true authentication error, from the SQL Server logs, it's impossible to state what the solution is, but here are a few possible reasons:
The Connection details are incorrect.
You are using the wrong LOGIN and/or password combination. Check that the creditials are correct against those stored in your password management software.
You are connecting to the wrong instance, and the LOGIN does not exist on the instance. Check that the instance details in your connection string are correct.
The LOGIN you are using is disabled. You need to log onto the server and re-enable it:
ALTER LOGIN someUser ENABLE;
The LOGIN doesn't have the connect permission. YOu need to log onto the server and GRANT it:
GRANT CONNECT SQL TO SomeUser
The LOGIN is trying to connect to a database it does not have a mapped USER on. You will need to CREATE the USER objects in the database(s) it requires access to, along with granting those USERs the needed permissions. You would create the USER with:
USE YourDatabase;
GO
CREATE USER SomeUser FOR LOGIN SomeUser;
There is a server trigger causing an error. Check that there are no triggers that are misbehaving that would cause the authentication to fail.
Another reason that would be exposed in the SQL Server log.

Finding NT user (Windows login) that uses SQL Server Login

As part of a security task I need to find all SQL Server logins that connect to the SQL server instance.
I create extended event for capture logins and filter only SQL Server logins.
The problem is that I can not tell from the SQL Server what was the NT user that was used.
Example:
From the xEvent I can see that user [sa] logged in to the SQL server instance and I can also see this client host name.
BUT , now I would like to know what was the domain account that was logged in to the client host name and use this SQL authentication.
I understand that SQL Server can not give this information but I would like yo know if I can get this info using PowerShell maybe.
I have the host name and the SID.
I could not find a solution here :
How to get Windows Log-in User Name for a SQL Log in User
You do not have a SID, that is a SQL Server SID (yes, there is a such a concept).
First, the answer: you do not. If you want to prevent SQL Logins, you deactivate SQL Logins, and that should be the end of the story.
Since there is no NTLM/Kerberos exchange for a SQL Server login, there is no way to find the credentials of the process/thread that initiated a SQL Login connection. However, you do have the host from where the connection was initiated and the process ID (they are the host_name and host_process_id columns in sys.dm_exec_sessions). Finding the credentials of the remote process is a trivial matter left as an exercise.
You've referenced having the SID, so if this is correct you can translate that to a user account. This works for both local users, and domain users:
$sid = 'S-1-5-21-3423846758-2645770820-3983523239-1001'
$objSID = New-Object System.Security.Principal.SecurityIdentifier($sid)
$objUser = $objSID.Translate( [System.Security.Principal.NTAccount])
($objUser.value -split '\\')[1]
Note: $objUser will contain either the computer name (for a local account) or the domain name (for an Active Directory account), so the split is to parse out the username only.
However, I'm currently unsure how you link this to which account they're using within SQL server (using SQL authentication) - I'm not sure where you're getting the SID information from (Windows event logs? Within SQL itself?).
Thank you all.
I managed to get the AD domain user by running a Get-WmiObject -Class Win32_Process :
1.Find the host_process_id and host_name using sys.dm_exec_sessions
2.Run a PowerShell:
Get-WmiObject -Class Win32_Process -ComputerName $host_name -Filter "ProcessId = '$($host_process_id )'" | ForEach-Object { $_.GetOwner() }

SQL Server Login error: Login failed for user 'NT AUTHORITY\SYSTEM'

I have created an application pool called "schoolPool" and assigned it to my web application. Identity for this pool has been set to LocalSystem.
When I try to access my database from within the application, i.e. open a SQL connection, I get the following error all the time:
Login failed for user 'NT AUTHORITY\SYSTEM'
I tried to add NT AUTHORITY/SYSTEM to SSMS (SQL Server Management Studio) logins, but it was already a principal, showing the following error:
Allow NT AUTHORITY/SYSTEM to server Role as sysadmin.
I tweaked the application settings a lot, changing the application pool's identity (in Windows 8.1's IIS) to LocalSystem, LocalService, NetworkService, and ApplicationPoolIdentity. However, all of them failed to solve the problem I had logging into my database.
Finally I set the pool identity on LocalSystem and thought why it might be preventing "NT AUTHRITY\SYSTEM" from opening a connection to my database. I opened up SQL Server Management Studio as "Administrator" and checked the Server Roles for NT AUTHORITY\SYSTEM under "logins" section. The default server role for this user was public by default. I also checked sysadmin and refreshed my web application form. This time it worked! Everything working perfectly now.
There is another fix. You should open Command Prompt (cmd) and write the following:
sqlcmd -S (server name)
select name from sys.server_principals where name = 'NT AUTHORITY\SYSTEM'
go
SP_ADDSRVROLEMEMBER 'NT AUTHORITY\SYSTEM','SYSADMIN'
go
The first line will give you an access to the sql server on you machine, the second will
take the following result NT AUTHORITY\SYSTEM an the stored procedure addsrvrolemember will add sysadmin to it. Be careful, because you have to type the following code the way it is.
Rerun following query which will assign 'NT SERVICE\MSSQLSERVER' to sysadmin
EXEC master..sp_addsrvrolemember #loginame = N'NT SERVICE\MSSQLSERVER', #rolename = N'sysadmin'
Musakkhir's answer of granting sysadmin seems poorly thought out as far as security goes, and Pinal's answer involved giving the unknown process db_owner rights, still almost certainly overkill. I've 'solved' it myself by simply granting "public" rights, which normally just allows CONNECT, but nothing else, even SELECT. If gets rid of the login error and stops flooding the error log, since it now logs in, but whatever unknown process is doing the connecting still can't do anything.
You should give your User ID and pwd of SQL server authentication login in the connectionStrings as User ID="username";pwd="yourpassword". You can use the following query
CREATE LOGIN login name WITH PASSWORD = 'password' ;
GO

remote powershell script executed by anonymous user

We are running deployment scripts using pstrami. Part of the deployment is to execute database migrations. The migrations are using an connection string with Integrated Security.
When the script executes on the remote machine the migrations fail with a sql error saying Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'
The person executing the script is a domain administrator. Other deployments that we run execute the remote scripts with the user who started the process.
The problem is that the credentials are not hopping to SQL Server for integrated security. You need to do the following:
On the server (the one that is making the SQL Server connection, as administrator run:
Enable-WSManCredSSP -Role server
On the client machine, as administrator run:
Enable-WSManCredSSP -Role client -DelegateComputer YOUR_SERVER_NAME
To open this up to all servers, you can run:
Enable-WSManCredSSP -Role client -DelegateComputer *
Finally, your invoke command make sure you run -authentication credssp. An example:
invoke-command -computername $remoteServer -authentication credssp -scriptblock { write-host "hello!" } -credential $credentials
This is the scenario:
You run the pstrami(deployment) script from desktopA. The script pushes your installation files to serverA. Then on serverA the scripts are run remotely as the person inititating the script from desktopA. One of the steps is to run a sql database upate with fluentmigrator using a connection string paramter using "integrated security" and the database is on serverB.
Connection string example:
$migration_db_connection = Data Source=serverB;Initial Catalog=PropertyDb;Integrated Security=SSPI;
.\migrate.exe /conn "$migration_db_connection" /db SqlServer /a $migration_assembly /profile DEBUG
Pstrami uses the powershell command invoke-command which uses the account you are running the script under as the default user. So, what happens is that when you run the script from desktopA as "jonDoe" it then authenticates on serverA. So your pstrami scripts run under "jonDoe" on serverA. When you execute the fluentmigrator script on serverA as "jonDoe", fluentmigrator returns an error Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'. In IIS, you run into an interesting situation when you need to access another resource off of the IIS server and certain fairly common situations occur. When using Integrated Security, anonymous access is disabled, and impersonation is turned on, a Windows security measure kicks in and doesn't allow your site to access resources on any network servers. (http://weblogs.asp.net/owscott/archive/2008/08/22/iis-windows-authentication-and-the-double-hop-issue.aspx)
This is how I got around the Windows Authentication and the Double Hop problem I ran into. Run your migration scripts directly on your sql database server and include it as a server target in your pstrami environments.
Example:
Environment "dev" -servers #(
Server "serverA" #("InstallWeb")
Server "serverB" #("RunMigrations")
)
More on Double Hop
http://www.spdoctor.net/Pages/message.aspx?name=login-failed-for-user-bdc
http://www.sqlservercentral.com/blogs/sqlsandwiches/2011/06/20/double-hop-of-doom/
I am not able to comment on your question and posting this as an answer. I will update the same later.
It may be due to SQL Server not having the login account for your windows login account. If that is the problem please add the logged in user to the SQL Server in the remote machine.
If this is already addressed, then you have the option of giving Rights as DB_Owner to " NT AUTHORITY\ANONYMOUS LOGON " on the SQL Server as well as on the specific database you are using.

Resources