632

I am experiencing an error when connecting MY DB which is in VM Role (I have SQL VM Role) from Azure Website. Both VM Role and Azure Website are in West zone. I am facing the following issue:

SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)]

I am able to connect to my DB using SSMS. Port 1433 is open on my VM role. What is wrong with my connection?

TarHalda
  • 1,050
  • 1
  • 9
  • 27
ZafarYousafi
  • 8,640
  • 5
  • 33
  • 39

31 Answers31

1169

2022 Update - This answer (as comments point out) provides an explanation and stop gap, but also offers some better recommendations including purchasing and installing a proper cert (thanks to numerous community edits).

Please see also the other highly voted answers in this thread, including the one by @Alex From Jitbit below about a breaking change when migrating from System.Data.Sql to Microsoft.Data.Sql (spoiler: Encrypt is now set to true by default).

Original answer:

You likely don't have a CA signed certificate installed in your SQL VM's trusted root store.

If you have Encrypt=True in the connection string, either set that to off (not recommended), or add the following in the connection string (also not recommended):

TrustServerCertificate=True

SQL Server will create a self-signed certificate if you don't install one for it to use, but it won't be trusted by the caller since it's not CA-signed, unless you tell the connection string to trust any server cert by default.

Long term, I'd recommend leveraging Let's Encrypt to get a CA signed certificate from a known trusted CA for free, and install it on the VM. Don't forget to set it up to automatically refresh. You can read more on this topic in SQL Server books online under the topic of "Encryption Hierarchy", and "Using Encryption Without Validation".

Thiago Silva
  • 14,183
  • 3
  • 36
  • 46
  • 4
    sorry my bad, TTrusted_Connection=False was set in connection string. setting it true works for me. Thanx anyway – ZafarYousafi Jul 24 '13 at 08:59
  • 17
    It is not good to advise setting `TrustServerCertificate` to `true`--this disables certificate checking. That's no better than just setting `Encrypt` to `false`! – Matt Thomas Mar 30 '17 at 19:34
  • 13
    The advice given "TrustServerCertificate=True" in this answer might make the problem go away, but it's terrible advice. Fix the cause, NOT the symptoms. The other part of the answer suggesting installing a CA signed cert is the way to go. – Mitch Wheat Oct 01 '18 at 10:53
  • 3
    In newer versions of SSMS you find a little option called "Trust server certificate" in the "Connection Properties" Tab. Checking this boy has the same effect as the commands listed above. – verfluecht Dec 18 '18 at 07:58
  • Do you have any pointers (not books) on how to install the certificate? All I'm finding is how to install it against a website in IIS. – Matt Arnold Feb 18 '20 at 17:35
  • 1
    @Mitch, I would like to understand what possible issues could occur if you turn this property to true? – Manoj Pandey Mar 26 '20 at 11:46
  • @MattArnold -- you can either double click a cert or use MMC (on Windows) with the Certificates snap-in. – BrainSlugs83 Aug 19 '20 at 21:44
  • 1
    This is bad advice because setting `TrustServerCertificate=true` causes the SQL client to ignore the certificate presented by the SQL server. This means that a hacker can intercept your SQL traffic and observe or modify it, which defeats the whole point of using encryption :|. – G S Jan 24 '22 at 07:18
  • 1
    In case with pyodbc: TrustServerCertificate=yes – Alekzander Feb 16 '22 at 16:10
  • Read more about how to setup a certificate [here](https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/enable-encrypted-connections-to-the-database-engine?view=sql-server-ver16). – Akira Yamamoto Oct 17 '22 at 00:55
  • Before anyone else needs to mald about this: "TrustServerCertificate" is only accepted if "Encrypt" exists in the connection string. By default encryption is enabled now with ODBC driver version 18 and just adding TrustServerCertificate without Encrypt will not do the job – Vinz Nov 19 '22 at 17:43
  • But if we really do trust the server certificate because the server is under our control and only accessible in the internal network, surely it's safe to just set `TrustServerCertificate` to true? – Shahin Dohan Feb 20 '23 at 13:15
347

I decided to add another answer, because this post pops-up as the first Google result for this error.

If you're getting this error after January 2022, possibly after migrating from System.Data.SqlClient to Microsoft.Data.SqlClient or just updating Microsoft.Data.SqlClient to version 4.0.0 or later, it's because MS has introduced a breaking change:

https://learn.microsoft.com/sql/connect/ado-net/introduction-microsoft-data-sqlclient-namespace?view=sql-server-ver15#breaking-changes-in-40

Breaking changes in 4.0

Changed Encrypt connection string property to be true by default.

The default value of the Encrypt connection setting has been changed from false to true. With the growing use of cloud databases and the need to ensure those connections are secure, it's time for this backwards-compatibility-breaking change.

Ensure connections fail when encryption is required

In scenarios where client encryption libraries were disabled or unavailable, it was possible for unencrypted connections to be made when Encrypt was set to true or the server required encryption.

The change was made in this SqlClient pull-request in August 2021, where there is additional discussion about the change.

The quick-fix is to add Encrypt=False to your connection-strings.

Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
Alex from Jitbit
  • 53,710
  • 19
  • 160
  • 149
  • 1
    Thanks, I updated a few packages or two and was wondering what the deal was. – Remi Despres-Smyth Mar 25 '22 at 17:12
  • 21
    The same also happens when using Entity Framework Core 7 (currently in preview), and the same fix works perfectly. Thanks for sharing – AFract Mar 31 '22 at 09:37
  • 1
    The solution (as opposed to a quick fix) is to get a real certificate, either from Let's Encrypt or a private CA – Charlieface Apr 21 '22 at 11:35
  • funny thing is that even you roll back from ef core 7 to ef core 6 the error still pops up. – akd Oct 27 '22 at 15:20
  • 4
    Adding the modified ConnectionStrings part if someone is wondering how to fix this. "ConnectionStrings": { "DefaultConnection": "Server=.;Database=Reactivity;Trusted_Connection=True;Encrypt=False" } – dotnetdev_2009 Dec 28 '22 at 22:07
  • quick fix is what exactly what I was looking for... anyway I think that Microsoft should better leave the default options, and let people decide when (and if) to eventually improve their own connections by using encryption, instead of changing it and create a panic... – BitQuestions Jan 19 '23 at 19:00
214

If you're using SQL Management Studio, please goto connection properties and click on "Trust server certificated" If you're using SQL Management Studio, please goto connection properties and click on "Trust server certificated"

ct.tan
  • 2,355
  • 1
  • 11
  • 4
  • 34
    It is not a bad advice per se. I would say that you can use it when you need to connect to a development server and do your job, such as coding. As a software developer I constantly struggle with DevOps who don't have time to fix things quickly and I can't afford to waste precious time against deadlines. Weighing data exposure turning off this option depends a lot of your environment, if it's local or remote, how admins set it up, IP restrictions and it can be easily mitigated with other workarounds. You can't say it's a bad advice without having a bit of information about your infrastructure. – OrizG Dec 29 '18 at 01:29
  • 1
    @OrizG I have a SQL Server installed on a local machine, and I use it for personal projects. At the moment, I don't want to spend a penny with it, so I got myself a free host and tried to configure the server in a way that I Ca-sign the certificates, and exchange them between the server and clients I'll be using to access it. However, because of the free host, I didn't manage to do that with Let's Encrypt. What exactly are the disadvantages of this solution, in comparison with properly doing the certificate exchange, with trusted CA signed certificates? – ccoutinho Feb 20 '20 at 23:29
  • What if im using EXCEL to get data from SQL Server DB? i have no setting like that – kucluk Oct 12 '21 at 04:36
  • @kucluk See answer from "Alex from Jitbit" above: Add `Encrypt=False` to your connection-strings – kevinarpe Jan 31 '23 at 05:35
  • You are an absolute rock star! This would have driven me around the bend after how many others I've ran into today, leading up to this exact issue (and resolution) Thank you kindly – Jeremy Little Apr 13 '23 at 04:33
85

If you're seeing this error message when attempting to connect using SSMS, add TrustServerCertificate=True to the Additional Connection Parameters.

Dale K
  • 25,246
  • 15
  • 42
  • 71
vmanne
  • 935
  • 7
  • 8
  • 29
    Mitch, you made this same comment on three answers to this question. It might be helpful to other readers if you provided some substantive information or link as to why this is "really, really bad advice." – Shoeless Oct 02 '18 at 15:26
  • 1
    @Shoeless Several comments on the accepted answer explain. – Tom Blodget Dec 05 '18 at 22:05
  • 1
    @Shoeless the same reason it's bad in any other certificate scenario -- it enables MITM attacks -- though with SQL Server, you're doing some infrastructure centric setup anyway, so MITM can be mitigated in other ways (i.e. restricting IP access and ensuring that the two machines are directly connected on the same network, etc.) -- Still, it's a bit cringe, but hey, Apple shipped MITM enabled devices for a couple of years before bothering to fix anything? -- So, it's probably fine. – BrainSlugs83 Aug 19 '20 at 21:43
  • This helps me and works on .Net 07! I add 'TrustServerCertificate=True' to connection string. – Aamir Jul 28 '23 at 13:49
52

I was getting this message in Entity Framework migrations. I was able to connect with Win Auth to the Sql Server and create table manually. But EF wouldn't work. This connection string finally worked

Server=MyServerName;Database=MyDbName;Trusted_Connection=SSPI;Encrypt=false;TrustServerCertificate=true
T.S.
  • 18,195
  • 11
  • 58
  • 78
  • 1
    This error has been driving me nuts. Your answer helped solve it, thank you! – root Sep 22 '22 at 17:56
  • Correct Answer so far – user1992910 Feb 14 '23 at 14:39
  • 1
    I uninstalled, installed again, repaired, restarted all of my SQL Server instances, several times. The same with SQL Server integration for VS22. The same with SSMS. Nothing worked. Copying and pasting the error from PMC brought me here. The solution was in these answer(s). Not even ChatGPT was able to help (probably because this is a recent issue). Thank you SO community. – carloswm85 May 20 '23 at 01:57
20

I added this 2 lines to the ConnectionString and it worked

Trusted_Connection=True
TrustServerCertificate=True
17
"ConnectionStrings": {
    "DefaultConnection": "Server=DESKTOP-O5SR0H0\\SQLEXPRESS;Database=myDataBase;Trusted_Connection=True;TrustServerCertificate=True;"
  }
}
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Sojib
  • 179
  • 1
  • 4
16

If you use EF Core 7 there is a breaking change that explained in the official Microsoft doc https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-7.0/breaking-changes#encrypt-defaults-to-true-for-sql-server-connections

dimmits
  • 1,999
  • 3
  • 12
  • 30
15

While the general answer was in itself correct, I found it did not go far enough for my SQL Server Import and Export Wizard orientated issue. Assuming you have a valid (and automatic) Windows Security based login:

ConnectionString

Data Source=localhost; 
Initial Catalog=<YOUR DATABASE HERE>; 
Integrated Security=True; 
Encrypt=True; 
TrustServerCertificate=True; 
User Instance=False

That can either be your complete ConnectionString (all on one line), or you can apply those values individually to their fields.

Orwellophile
  • 13,235
  • 3
  • 69
  • 45
15

Turn off encryption in the connection string. You can achieve this by appending the following to your connection string:

encrypt=false
  • This will work as in EF Core 7 there are some breaking changes and due to that, this issue is occurring. https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-7.0/breaking-changes#encrypt-defaults-to-true-for-sql-server-connections – Nikesh Pandya May 23 '23 at 04:33
13
PM> Scaffold-DbContext "Server=localhost;Database=BookStoresDB;Trusted_Connection=True;TrustServerCertificate=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Using "TrustServerCertificate=True" solved Error "A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)"

Md Shahriar
  • 2,072
  • 22
  • 11
12

Add Encrypt=False to your connection string and that's it

T.S.
  • 18,195
  • 11
  • 58
  • 78
J S
  • 591
  • 6
  • 11
10

If You are trying to access it through Data Connections in Visual Studio 2015, and getting the above Error, Then Go to Advanced and set TrustServerCertificate=True for error to go away.

Bhavjot
  • 544
  • 5
  • 16
  • 9
    It is not a bad advice per se. I would say that you can use it when you need to connect to a development server and do your job, such as coding. As a software developer I constantly struggle with DevOps who don't have time to fix things quickly and I can't afford to waste precious time against deadlines. Weighing data exposure turning off this option depends a lot of your environment, if it's local or remote, how admins set it up, IP restrictions and it can be easily mitigated with other workarounds. You can't say it's a bad advice without having a bit of information about your infrastructure. – OrizG Dec 29 '18 at 01:30
8

In my case, it wasn't enough to extend the connection string by
Encrypt=false;TrustServerCertificate=true;

I still had to type in the NuGet console:

update-database -verbose

Troom
  • 431
  • 6
  • 10
7

If you use Version 18 and access via pyodbc, it is "TrustServerCertificate=yes", you need to add to the connection

Andi Schroff
  • 1,156
  • 1
  • 12
  • 18
6

I got this Issue while importing Excel data into SQLDatabase through SSMS. The solution is to set TrustServerCertificate = True in the security section

Dale K
  • 25,246
  • 15
  • 42
  • 71
Kanna Reddy
  • 309
  • 4
  • 5
5

For those who don't like the TrustServerCertificate=True answer, if you have sufficient access you can export the SQL Server certificate and install where you're trying to connect from. This probably doesn't work for a SQL Server self-generated certificate but if you used something like New-SelfSignedCertificate you can use MMC to export the certificate, then MMC on the client to import it.

On SQL Server:

  • In MMC add the certificate Snap-In
  • Browse to Certificates > Personal > Certificate
  • Select the new certificate, right-click, and select All Tasks > Manage Private Keys (this step and the following is part of making the key work with SQL server)
  • Add the identity running SQL Server (look the identity up in Services if in doubt) with READ permission.
  • Select the new certificate, right-click, and select All Tasks > Export...
  • Use default settings and save as a file.

On the client:

  • Use MMS with the same snap-in choices and in Certificates > Trusted Root Certification Authorities right-click Certificates and select All Tasks > Import...
  • Import the previously exported file

(I was doing everything on the same server and still had issues with SSMS complaining until I restarted the SQL instance. Then I could connect encrypted without the Trust... checkbox checked)

Tommy Hansen
  • 105
  • 1
  • 6
5

When you are using SqlPackage.exe, the Encrypt=False in your connectionstring is ignored.

Add /TargetTrustServerCertificate:true to the SqlPackage command to fix this issue.

MonkeyDreamzzz
  • 3,978
  • 1
  • 39
  • 36
5

In my case i have chaged multiple time in appsettings.json but not changing in the development version of appsettingsDevelpment.json. after change the developemnt version of appsettings its works fine.

"ConnectionStrings": {
    "DefaultConnection": "Server=DESKTOP-M08SV8P;Database=ActivityProject;Trusted_Connection=True;TrustServerCertificate=True;"
  },

enter image description here

Hoque MD Zahidul
  • 10,560
  • 2
  • 37
  • 40
3

If you are using any connection attributes mentioned in the answers, the values accepted are yes/no , if true/false doesn't seem to work.

TrustServerCertificate - Accepts the strings "yes" and "no" as values. The default value is "no", which means that the server certificate will be validated.

Using ODBC 18.0 - hope it helps.

Connection String Attributes

Zedverse07
  • 71
  • 6
3

I had the same issue after migrating a project from .NET 5 to .NET 6. I have tried suggested solutions (either TrustServerCertificate=True or Encrypt=False) and they worked as expected but I had a limitation to not change connection string. So if that is the case, you can still use System.Data.SqlClient as a nuget package. Like explained here it is still maintained but all the new stuff will go to Microsoft.Data.SqlClient.

Hasan
  • 1,243
  • 12
  • 27
3

In simple this is enough,if you are running locally

"ConnectionString": "Data Source=(local);Initial Catalog=BlazorDashboardDb;TrustServerCertificate=True;Integrated Security=True;", 1

TrustServerCertificate makes SSL handling Integrated Security makes windows validation,if sql authentication the add parameter as "User ID=adminUsername;Password=adminSecretPasswordwhatever"

TO cover all sceanrio then below helps "Data Source=(local);Initial Catalog=BlazorDashboardDb;TrustServerCertificate=True;Trusted_Connection=True;Integrated Security=True;MultipleActiveResultSets=true;Encrypt=True;"

Trusted_Connection is for trusting the mode of connection Encrypt is for crednetials

Connecting to server(az-sql) ex: "Server=tcp:firstserver.database.windows.net,1433;Initial Catalog=First;Persist Security Info=False;User ID=adminUsername;Password=adminSecretPasswordwhatever;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=True;Connection Timeout=30;"

2

I ran into this error trying to run the profiler, even though my connection had Trust server certificate checked and I added TrustServerCertificate=True in the Advanced Section. I changed to an instance of SSMS running as administrator and the profiler started with no problem. (I previously had found that when my connections even to local took a long time to connect, running as administrator helped).

Dale K
  • 25,246
  • 15
  • 42
  • 71
Bill
  • 21
  • 3
2

Got hit by the same issue while accessing SQLServer from IIS. Adding TrustServerCertificate=True did not help.

Could see a comment in MS docs: Make sure the SQLServer service account has access to the TLS Certificate you are using. (NT Service\MSSQLSERVER)

Open personal store and right click on the certificate -> manage private keys -> Add the SQL service account and give full control.

Restart the SQL service. It worked.

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
Kaavya T
  • 31
  • 4
2

Short notice. If you're using AWS RDS you can get the certificates from truststore.pki.rds.amazonaws.com. Details with particular links can be found in this documentation: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL.html.

Simply download the appropriate certificate and install it on your host.

Sergey Nikitin
  • 845
  • 2
  • 13
  • 25
1

If you have created an ODBC connection to the server (using ODBC Driver 18 for SQL server) in ODBC settings (32 or 64), configure the connection and press Next 3 times. In the final screen, there is a "Trust server certificate" checkbox in the middle. Set it to checked. That will do the trick. Adding "TrustServerCertificate=True" to the connectionstring as suggested in other answers did not work for me.

ODBC Data Sources (32 or 64)

FaultyOverflow
  • 153
  • 1
  • 9
1

Alternatively, create a Service Master Key (SMK) based on an exported server certficate from your MMC console - export as a pfx with a password. Using that certificate, engage in the following steps

CREATE MASTER KEY ENCRYPTION BY PASSWORD='Password1234!@#$'

From you exported certificate, run the batch file

@echo off 
echo Create a new password at the pop-up. 
echo This is NOT the same as the one you provided above. 
echo You'll be asked to create, confirm and re-enter the password (total 3 times) 
echo Creating Certificate (CER) and Key (PVK). 
"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Bin\x64\makecert.exe" -sv %1.pvk -n "CN=%2" %1.cer 
echo On prompt, again (4th and last time) provide the password you just created. 
echo Merging the two files into a PFX now. 
"C:\Program Files (x86)\Windows Kits\8.0\bin\x64\pvk2pfx.exe" -pvk %1.pvk -spc %1.cer -pfx %1.pfx -po %3

CREATE YOUR ASSYMETRIC KEY

CREATE CERTIFICATE MYDB_ASYMMETRIC_CA_KEY  FROM FILE='C:\MYDB_ASSYMETRIC_CA_KEY.cer'
  WITH PRIVATE KEY(FILE='C:\ MYDB_ASSYMETRIC_CA_KEY.pvk'
  DECRYPTION BY PASSWORD='Password1234!@#$'); 

For redundancy, check that your master key is in place... it is a must

ALTER MASTER KEY REGENERATE WITH ENCRYPTION BY PASSWORD='Password1234!@#$'

NOW CREATE THE ACTUAL KEY

CREATE CERTIFICATE MYDB_ASYMMETRIC_CA_KEY FROM FILE='c:\MYDB_ASYMMETRIC_CA_KEY.cer' 
WITH PRIVATE KEY (FILE='C:\MYDB_ASYMMETRIC_CA_KEY.pvk',
DECRYPTION BY PASSWORD='Password1234!@#$');

ALWAYS ALWAYS Backup your certificate in the event you need to move to another server. You'll need it to decrypt your backup files

BACKUP CERTIFICATE MYDB_ASYMMETRIC_CA_KEY TO FILE='MYDB_ASYMMETRIC_CA_KEY_BACKUP.bkp' 
WITH PRIVATE KEY(FILE='MYDB_ASYMMETRIC_CA_KEY_BACKUP.bkp',
ENCRYPTION BY PASSWORD='Password1234!@#$'); 

CREATE Database Level Encryption to wrangle in your certificate

CREATE DATABASE ENCRYPTION KEY WITH ALGORITHM=AES_256
ENCRYPTION BY SERVER CERTIFICATE MYDB_ASYMMETRIC_CA_KEY

Check the steps above before going to the next step as from here on in, your database will be encrypted with an Assymentric Key - if you haven't backed it up (the key) and you try to restore from another server, it won't be possible without all the above steps in place.

On another database - for example a Staging Database - Restore the Master key from the certificate.

You have your Service Master Key in place, to encrypt the database, you need to encrypt the Database Master Key as this allows the export of the database to another server using the certificate you've created above.

TESTING THE Certificate by importing to another server

RESTORE MASTER KEY FROM FILE='C:\ MYDB_ASSYMETRIC_CA_KEY_BACKUP'
 DECRYPTION BY PASSWORD='Password1234!@#$', ENCRYPTION BY PASSWORD='Password1234!@#$'
 ,[FORCE]

Check to see if the Content exists on the alternate server (this will work on the primary as well)

USE [AUTHORIZATION]; 
 IF NOT EXISTS ( SELECT
 1
 FROM
 sys.dm_database_encryption_keys
 WHERE
 DB_NAME(database_id) = DB_NAME() )
 SELECT
 DB_NAME() AS [Database Name]
 ,'No database encryption key present, no encryption' AS [Encryption
 State] 
 ELSE
 SELECT
 DB_NAME(database_id) AS [Database Name]
 ,CASE encryption_state
 WHEN 0 THEN 'No database encryption key present, no encryption'
 WHEN 1 THEN 'Unencrypted'
 WHEN 2 THEN 'Encryption in progress'
 WHEN 3 THEN 'Encrypted'
 WHEN 4 THEN 'Key change in progress'
 WHEN 5 THEN 'Decryption in progress'
 WHEN 6 THEN 'Protection change in progress'
 END AS [Encryption State]
 FROM
 sys.dm_database_encryption_keys
 WHERE
 DB_NAME(database_id) = DB_NAME(); 
jamiel22
  • 117
  • 6
1

Guid on how to make encrypt = False using SSMS. Only for local development purpose. Not recommended for production use cases.

  1. Click on options>>
  2. As shown in the pic, de-select Encrypt connection.
  3. Click connect. <<** boom **>>.

enter image description here

jeevu94
  • 477
  • 4
  • 16
0

The same can be achieved from ssms client itself. Just open the ssms, insert the server name and then from options under heading connection properties make sure Trust server certificate is checked.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Manas
  • 1
0

I was getting the same error when trying to connect to MS SQL Server instance hosted on Google Cloud Platform using SSMS with unchecked Trust server certificate under the connection properties tab. I managed to trust the certificate by importing the GCP's provided certificate's authority to my local computer's list of Trusted Root Certification Authorities.

Read full description and resolution here.

Rizwan
  • 71
  • 8
0

Well in my case the Database was bad. When I re created a new database name the error got resolved. It's an error coming from SQL Server database. Try re creating a new database.