Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 31 - Encryption(ssl/tls) handshake failed) #633

Closed
machoubie opened this issue Jul 3, 2020 · 47 comments

Comments

@machoubie
Copy link

Hi,
I am faced the issue bellow when trying connection From .net core container to windows mssql .

Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 31 - Encryption(ssl/tls) handshake failed)
---> System.IO.EndOfStreamException: End of stream reached
at Microsoft.Data.SqlClient.SNI.SslOverTdsStream.ReadInternal(Byte[] buffer, Int32 offset, Int32 count, CancellationToken token, Boolean async)
at Microsoft.Data.SqlClient.SNI.SslOverTdsStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.FixedSizeReader.ReadPacket(Stream transport, Byte[] buffer, Int32 offset, Int32 count)
at System.Net.Security.SslStream.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.ProcessAuthentication(LazyAsyncResult lazyResult, CancellationToken cancellationToken)
at System.Net.Security.SslStream.AuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions)
at System.Net.Security.SslStream.AuthenticateAsClient(String targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, Boolean checkCertificateRevocation)
at System.Net.Security.SslStream.AuthenticateAsClient(String targetHost)
at Microsoft.Data.SqlClient.SNI.SNITCPHandle.EnableSsl(UInt32 options)
at Microsoft.Data.SqlClient.SNI.SNIProxy.EnableSsl(SNIHandle handle, UInt32 options)
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at Microsoft.Data.SqlClient.TdsParser.ConsumePreLoginHandshake(Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean& marsCapable, Boolean& fedAuthRequired) at Microsoft.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover, SqlAuthenticationMethod authType) at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool) at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)
at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry, SqlConnectionOverrides overrides)
at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides)
at Microsoft.Data.SqlClient.SqlConnection.Open()
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection(Boolean errorsExpected)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.InitializeReader(DbContext _, Boolean result) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func3 operation, Func3 verifySucceeded) at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.MoveNext()
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
at TEST.Api.DAL.EnqueuingToDb.DbMilor2Context.EnqueueData(ApiCallIdentification metadatas, String json) in /src/TEST/DAL/EnqueuingToDb/DbMilor2Context.cs:line 57
at TEST.Api.Business.EnqueuingToDb.Enqueuing.Create() in /src/TEST/Business/EnqueuingToDb/Enqueuing.cs:line 51
at TEST.Api.Models.ActionFilters.DataEnqueuingFilterAttribute.OnActionExecuting(ActionExecutingContext context) in /src/TEST/Models/ActionFilters/DataEnqueuingFilter.cs:line 109
at Microsoft.AspNetCore.Mvc.Filters.ActionFilterAttribute.OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
ClientConnectionId:490aab56-2f44-4824-b5a1-907042f6e801 Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 31 - Encryption(ssl/tls) handshake failed)

Docker version:
Client: Docker Engine - Community
Version: 19.03.12
API version: 1.40
Go version: go1.13.10
Git commit: 48a66213fe
Built: Mon Jun 22 15:45:36 2020
OS/Arch: linux/amd64
Experimental: false

Server: Docker Engine - Community
Engine:
Version: 19.03.12
API version: 1.40 (minimum version 1.12)
Go version: go1.13.10
Git commit: 48a66213fe
Built: Mon Jun 22 15:44:07 2020
OS/Arch: linux/amd64
Experimental: false
containerd:
Version: 1.2.13
GitCommit: 7ad184331fa3e55e52b890ea95e65ba581ae3429
runc:
Version: 1.0.0-rc10
GitCommit: dc9208a3303feef5b3839f4323d9beb36df0a9dd
docker-init:
Version: 0.18.0
GitCommit: fec3683

Host info :
Kernel Version: 5.3.0-1031-azure
Operating System: Ubuntu 18.04.4 LTS
OSType: linux
Architecture: x86_64

Connection String :

Data Source=TESTSERVER2INT\TESTSQL02INT,52810;Initial Catalog=Test;User ID=test_user;Password=****;Integrated Security=False

Thank you in advance for your Help

@karinazhou
Copy link
Member

Hi @machoubie ,

From the docker info, it's hard to tell what SQL server version you are using. Could you provide more information about your server? And what docker images you are using? Is the Ubuntu 18.04 OS the actual system or the docker container you are using to connect to the server?

I assume that you are using the Microsoft.Data.SqlClient v2.0.0 because you have seen the "End of stream reached" error message which is recently introduced by PR 577. This error may be related to Server certificate force encryption #609 or lower TLS version used by the server (quote from 201).

You can check the following settings first on your side:

  1. Check if the SQL Server has Force Encryption as YES.
  2. If yes, add Trust Server Certificate = true in your connection string or Set Force Encryption to NO.

If the above two steps don't solve your issue, you may face a similar case when your server is using lower version of TLS. If possible, you can try to write a simple .NET core application to connect to your target server and see if you get warning message like Security Warning: The negotiated TLS1.0 is an insecure protocol and is supported for backward compatibility only. The recommended protocol version is TLS 1.2 and later. If you see such warning, either your server or your client environment is using lower TLS version to communicate with the other.

@madhon
Copy link

madhon commented Jul 6, 2020

I have exactly the same issue, all i did was update the package from 1.1.3 to 2.0.0 ... it then broke, downgrading back to 1.1.3 made it work again. This leads me to believe its not SQL Server at fault, its the sqlclient package

@madhon
Copy link

madhon commented Jul 6, 2020

ee the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.

************** Exception Text **************
Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: Shared Memory Provider, error: 36 - The Shared Memory dll used to connect to SQL Server 2000 was not found) ---> System.ComponentModel.Win32Exception (0x80004005): The system cannot find the file specified
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) in H:\tsaagent2\_work\11\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlInternalConnection.cs:line 779 at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) in H:\tsaagent2\_work\11\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\TdsParser.cs:line 1668 at Microsoft.Data.SqlClient.TdsParser.ConsumePreLoginHandshake(SqlAuthenticationMethod authType, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, ServerCertificateValidationCallback serverCallback, ClientCertificateRetrievalCallback clientCallback, Boolean& marsCapable, Boolean& fedAuthRequired) in H:\tsaagent2\_work\11\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\TdsParser.cs:line 1293 at Microsoft.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover, Boolean isFirstTransparentAttempt, SqlAuthenticationMethod authType, String certificate, ServerCertificateValidationCallback serverCallback, ClientCertificateRetrievalCallback clientCallback, Boolean useOriginalAddressInfo, Boolean disableTnir) in H:\tsaagent2\_work\11\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\TdsParser.cs:line 640 at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover, Boolean isFirstTransparentAttempt, Boolean disableTnir) in H:\tsaagent2\_work\11\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlInternalConnectionTds.cs:line 2251 at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) in H:\tsaagent2\_work\11\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlInternalConnectionTds.cs:line 1873 at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) in H:\tsaagent2\_work\11\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlInternalConnectionTds.cs:line 1685 at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, ServerCertificateValidationCallback serverCallback, ClientCertificateRetrievalCallback clientCallback, DbConnectionPool pool, String accessToken, SqlClientOriginalNetworkAddressInfo originalNetworkAddressInfo, Boolean applyTransientFaultHandling) in H:\tsaagent2\_work\11\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlInternalConnectionTds.cs:line 536 at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) in H:\tsaagent2\_work\11\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlConnectionFactory.cs:line 143 at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) in H:\tsaagent2\_work\11\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionFactory.cs:line 163 at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) in H:\tsaagent2\_work\11\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionPool.cs:line 943 at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) in H:\tsaagent2\_work\11\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionPool.cs:line 2000 at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) in H:\tsaagent2\_work\11\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionPool.cs:line 1412 at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) in H:\tsaagent2_work\11\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionPool.cs:line 1296
at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) in H:\tsaagent2\_work\11\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionFactory.cs:line 354 at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) in H:\tsaagent2_work\11\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionInternal.cs:line 766
at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) in H:\tsaagent2\_work\11\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionClosed.cs:line 71 at Microsoft.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry) in H:\tsaagent2_work\11\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlConnection.cs:line 1946
at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry, SqlConnectionOverrides overrides) in H:\tsaagent2\_work\11\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlConnection.cs:line 1934 at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides) in H:\tsaagent2\_work\11\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlConnection.cs:line 1495 at Microsoft.Data.SqlClient.SqlConnection.Open() in H:\tsaagent2\_work\11\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlConnection.cs:line 1466 at Dapper.SqlMapper.<QueryImpl>d__1401.MoveNext() in //Dapper/SqlMapper.cs:line 1078
at System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source) at Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable1 commandTimeout, Nullable`1 commandType) in /
/Dapper/SqlMapper.cs:line 721
at WindowsFormsApp1.Form1.LoadLeadButton_Click(Object sender, EventArgs e) in M:\development\R1\R1\WindowsFormsApp1\Form1.cs:line 21
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
ClientConnectionId:67e04f97-acbb-48e7-a4d7-918df00c2e58
Error Number:2,State:0,Class:20

************** Loaded Assemblies **************
mscorlib
Assembly Version: 4.0.0.0
Win32 Version: 4.8.4180.0 built by: NET48REL1LAST_B
CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll

WindowsFormsApp1
Assembly Version: 1.0.0.0
Win32 Version: 1.0.0.0
CodeBase: file:///M:/development/R1/R1/WindowsFormsApp1/bin/Debug/WindowsFormsApp1.exe

System.Windows.Forms
Assembly Version: 4.0.0.0
Win32 Version: 4.8.4084.0 built by: NET48REL1
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll

System
Assembly Version: 4.0.0.0
Win32 Version: 4.8.4084.0 built by: NET48REL1
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b77a5c561934e089/System.dll

System.Drawing
Assembly Version: 4.0.0.0
Win32 Version: 4.8.4084.0 built by: NET48REL1
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll

System.Configuration
Assembly Version: 4.0.0.0
Win32 Version: 4.8.4084.0 built by: NET48REL1
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Configuration/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll

System.Core
Assembly Version: 4.0.0.0
Win32 Version: 4.8.4180.0 built by: NET48REL1LAST_B
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Core/v4.0_4.0.0.0__b77a5c561934e089/System.Core.dll

System.Xml
Assembly Version: 4.0.0.0
Win32 Version: 4.8.4084.0 built by: NET48REL1
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Xml/v4.0_4.0.0.0__b77a5c561934e089/System.Xml.dll

System.Data
Assembly Version: 4.0.0.0
Win32 Version: 4.8.4084.0 built by: NET48REL1
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_32/System.Data/v4.0_4.0.0.0__b77a5c561934e089/System.Data.dll

Microsoft.Data.SqlClient
Assembly Version: 2.0.20168.4
Win32 Version: 2.00.20168.4
CodeBase: file:///M:/development/R1/R1/WindowsFormsApp1/bin/Debug/Microsoft.Data.SqlClient.DLL

System.Transactions
Assembly Version: 4.0.0.0
Win32 Version: 4.8.4084.0 built by: NET48REL1
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_32/System.Transactions/v4.0_4.0.0.0__b77a5c561934e089/System.Transactions.dll

Dapper
Assembly Version: 2.0.0.0
Win32 Version: 2.0.35.21366
CodeBase: file:///M:/development/R1/R1/WindowsFormsApp1/bin/Debug/Dapper.DLL

System.Xml.Linq
Assembly Version: 4.0.0.0
Win32 Version: 4.8.4084.0 built by: NET48REL1
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Xml.Linq/v4.0_4.0.0.0__b77a5c561934e089/System.Xml.Linq.dll

System.EnterpriseServices
Assembly Version: 4.0.0.0
Win32 Version: 4.8.4084.0 built by: NET48REL1
CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_32/System.EnterpriseServices/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.EnterpriseServices.dll

************** JIT Debugging **************
To enable just-in-time (JIT) debugging, the .config file for this
application or computer (machine.config) must have the
jitDebugging value set in the system.windows.forms section.
The application must also be compiled with debugging
enabled.

For example:

When JIT debugging is enabled, any unhandled exception
will be sent to the JIT debugger registered on the computer
rather than be handled by this dialog box.

@ErikEJ
Copy link
Contributor

ErikEJ commented Jul 6, 2020

@madhon It is a documented breaking change in the 2.0 provider, yes. https://erikej.github.io/sqlclient/efcore/2020/06/22/sqlclient-2-breaking-changes.html

@madhon
Copy link

madhon commented Jul 6, 2020

@madhon It is a documented breaking change in the 2.0 provider, yes. https://erikej.github.io/sqlclient/efcore/2020/06/22/sqlclient-2-breaking-changes.html

Why would that connection string value be force required now ? Its effectively saying trust the certificate regardless of if it verifies up to a trusted root certificate or not ?

I was under the impression that parameter was only to override untrusted certificates ?

@madhon
Copy link

madhon commented Jul 6, 2020

The equivalent of the following code to override trust of certs when accessing web apis/sites

ServicePointManager
.ServerCertificateValidationCallback +=
(sender, cert, chain, sslPolicyErrors) => true;

@machoubie
Copy link
Author

machoubie commented Jul 6, 2020

@karinazhou i am using dotnet/core/aspnet:3.0-buster-slim docker image to run my apps , the tests you suggest don't work for me
the sql server version is 2016

@machoubie
Copy link
Author

another thing, when i add Encrypt=False to my connectionString , the sqlclient still use ssl for th connection

@cheenamalhotra
Copy link
Member

@machoubie

Please ensure your server is not enforcing SSL if it's an on-premise SQL Server, see comment here: #609 (comment)

@machoubie
Copy link
Author

I confirm that the server is not enforcing ssl

@madhon
Copy link

madhon commented Jul 6, 2020

Ours isn’t enforcing either

@cheenamalhotra
Copy link
Member

cheenamalhotra commented Jul 6, 2020

Ok, I got a bit confused in discussions above.

To clarify, SSL/TLS handshake is always performed never-the-less client requests encryption, it's part of login flow. But, whether the stream is going to be encrypted and certificates are validated are not, depends on client/server settings where "Force Encryption" plays a role, which doesn't seem to be the case here.

Also, I see two different stack traces in above discussions:
Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 31 - Encryption(ssl/tls) handshake failed) ---> System.IO.EndOfStreamException: End of stream reached
and
Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: Shared Memory Provider, error: 36 - The Shared Memory dll used to connect to SQL Server 2000 was not found) ---> System.ComponentModel.Win32Exception (0x80004005): The system cannot find the file specified (Not possible on Linux as mentioned in the issue description)

If both issues are different, let's stick to issue in description first.

@machoubie provider: SSL Provider, error: 31 .. System.IO.EndOfStreamException: End of stream reached issue is possible, when client does not support TLS 1.0/1.1 versions whereas Server does not support TLS 1.2 > leading to server not responding to client's request as no "trust" is established. To fix this error, you need to ensure TLS 1.2 is enabled on Server and is available to be used to connect. If you are not sure it is enabled, you can connect from a Windows client where lower TLS versions are enabled and verify if a lower TLS protocol version is negotiated by looking at "warning" thrown by driver.

@madhon On the other hand, for stack trace regarding "provider: Shared Memory Provider, error: 36" , we'll need more details regarding your environment setup and how can we reproduce this issue?

@karinazhou
Copy link
Member

karinazhou commented Jul 6, 2020

@machoubie According to what @cheenamalhotra has suggested, your issue looks similar to this one #201 . I can see some other users facing the same issue due to TLS version mismatching. Probably, your Debian image is using TLS 1.2 by default while your server is using a lower TLS version. If you can confirm that your SQL Server is using old TLS version, for example, by connecting from a Windows application and check the TLS version warning message. You can either enable TLS 1.2 on your SQL Server or try some suggestions like switching to a 3.0-bionic image (Ubuntu 18.04) if possible or bring back the minimal TLS support version on Debian if upgrading server's TLS version is not an option for you. Other ways you can also try :
#201 (comment)
#201 (comment)

And here is the link about how to enable TLS 1.2 on SQL Server.

@goolzerg
Copy link

goolzerg commented Jul 7, 2020

@machoubie According to what @cheenamalhotra has suggested, your issue looks similar to this one #201 . I can see some other users facing the same issue due to TLS version mismatching. Probably, your Debian image is using TLS 1.2 by default while your server is using a lower TLS version. If you can confirm that your SQL Server is using old TLS version, for example, by connecting from a Windows application and check the TLS version warning message. You can either enable TLS 1.2 on your SQL Server or try some suggestions like switching to a 3.0-bionic image (Ubuntu 18.04) if possible or bring back the minimal TLS support version on Debian if upgrading server's TLS version is not an option for you. Other ways you can also try :
#201 (comment)
#201 (comment)

And here is the link about how to enable TLS 1.2 on SQL Server.

+1 It worked for me. I've changed the minimal TLS version to 1.0

@arthurdelduque
Copy link

+1 It worked for me. I've changed the minimal TLS version to 1.0

@machoubie
Copy link
Author

+1 It worked for me.
Thank you for you help

@cheenamalhotra
Copy link
Member

I'd like to add again that lowering TLS version would work, but it's not recommended solution as TLS 1.0 and 1.1 are insecure protocols. Ideal solution is to upgrade/enable target SQL Servers to support TLS 1.2 protocol.

@kfman
Copy link

kfman commented Oct 8, 2020

Just add

RUN sed -i 's/DEFAULT@SECLEVEL=2/DEFAULT@SECLEVEL=1/g' /etc/ssl/openssl.cnf

to your Dockerfile right above the ENTRYPOINT

@johanskoldekrans
Copy link

This last entry fixed it for us. TrustServerCertificate=false was not enough. Kudos to @kfman for the save!

@davidwest
Copy link

That did it for me as well, thanks!

@Leonardo-Ferreira
Copy link

Just add

RUN sed -i 's/DEFAULT@SECLEVEL=2/DEFAULT@SECLEVEL=1/g' /etc/ssl/openssl.cnf

to your Dockerfile right above the ENTRYPOINT

Unfortunately that does not solve for .Net 5

@cheenamalhotra
Copy link
Member

@Leonardo-Ferreira

You're possible hitting this issue:
https://docs.microsoft.com/en-us/dotnet/core/compatibility/cryptography/5.0/default-cipher-suites-for-tls-on-linux

Could you try their recommendations?

@Leonardo-Ferreira
Copy link

Leonardo-Ferreira commented Mar 2, 2021

@cheenamalhotra I just did try their recommendation. My openssl.cnf file now points a CipherString = ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256 but my error persists... the good old Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 31 - Encryption(ssl/tls) handshake failed) still happens...

I also replaced the MinProtocol = TLSv1.2 for 1.0, but that didn't seem to affect nothing

@cheenamalhotra
Copy link
Member

@Leonardo-Ferreira
Copy link

@charlienilsson tks for the article, but the error persists... I have tried several combinations... even using other images such as 5.0-focal-amd64... the iteration process between tests is quite slow for me cause I can only reproduce on QA env. Ironically the DEV database is TLSv1.2 enabled... to be precise I tested:

MinProtocol = TLSv1
CipherString = ECDHE-ECDSA-bla bla bla

MinProtocol = TLSv1
CipherString = DEFAULT@SECLEVEL=1

using both images 5.0 and 5.0-focal-amd64

@Gavin1Sinai
Copy link

Gavin1Sinai commented Mar 3, 2021

I had this when using wrong version of SqlClient -error message kept coming up but only on Linux Container not on Windows - I had latest .net 5 but somehow my SqlClient was file stamped 2017. Issue resolved by removing System.Data.SqlCient from the project and installing Microsoft.Data.SqlClient using Nuget.

@johanskoldekrans
Copy link

Yes Microsoft.Data.SqlClient is platform independent and System.Data isnt. Make sure that the dll for Microsoft.Data.SqlClient is in the bin folder of the container. We have everything on net5 and it is working like a charm.

@Leonardo-Ferreira
Copy link

tks @Gavin1Sinai and @johanskoldekrans but im already using Microsoft.Data. I just found out that the database there is a SQL Server 2008 R2...

@lleonk
Copy link

lleonk commented Apr 14, 2021

@charlienilsson tks for the article, but the error persists... I have tried several combinations... even using other images such as 5.0-focal-amd64... the iteration process between tests is quite slow for me cause I can only reproduce on QA env. Ironically the DEV database is TLSv1.2 enabled... to be precise I tested:

MinProtocol = TLSv1
CipherString = ECDHE-ECDSA-bla bla bla

MinProtocol = TLSv1
CipherString = DEFAULT@SECLEVEL=1

using both images 5.0 and 5.0-focal-amd64

I was with the same problem
A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 31 - Encryption(ssl/tls) handshake failed)

I manage to work with 5.0-buster-slim and including only this changes in dockerfile:

RUN sed -i 's/DEFAULT@SECLEVEL=2/ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256/g' /etc/ssl/openssl.cnf
RUN sed -i 's/DEFAULT@SECLEVEL=2/ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256/g' /usr/lib/ssl/openssl.cnf

@wdrdres3qew5ts21
Copy link

Hello Everyone I had try run everythin that could possibly combine.
But I still got problem when I connect to SQL Server 2008.
I had try to use Container of DotNet 3.0, 3.1, 5.0 but it seem all of them are not working.
But it working correctly when I run my Dotnet program in Window Laptop (which need enable SMB 1.0)
But it not working when deploy to Ubuntu container.

# FROM mcr.microsoft.com/dotnet/sdk:5.0-buster-slim AS build-env
# FROM mcr.microsoft.com/dotnet/sdk:5.0-focal AS build-env
#FROM mcr.microsoft.com/dotnet/core/sdk:3.1-bionic AS build-env
FROM mcr.microsoft.com/dotnet/core/sdk:3.0-bionic AS build-env
WORKDIR /app

COPY *.csproj ./
RUN dotnet restore


COPY . ./
RUN dotnet publish -c Release -o out

#FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-bionic AS final
FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-bionic AS final
# from mcr.microsoft.com/dotnet/aspnet:5.0-focal
# from mcr.microsoft.com/dotnet/aspnet:5.0-buster-slim
WORKDIR /app
EXPOSE 5001
ENV ASPNETCORE_ENVIRONMENT=Development
ENV DOTNET_USE_POLLING_FILE_WATCHER=true  
ENV DB_SERVER=http://mydb.com 
ENV DB_PORT=5000
ENV DB_USER=xxx
ENV DB_PASSWORD=xxx
ENV DB_TRUSTED_CONNECTION=False
run apt-get update -y && apt-get install vim -y && apt-get install wget -y


ENV ASPNETCORE_URLS=http://+:5000  
COPY --from=build-env /app/out .

RUN sed -i '1i openssl_conf = default_conf' /etc/ssl/openssl.cnf && echo "\n\n[default_conf]\nssl_conf = ssl_sect\n[ssl_sect]\nsystem_default = system_default_sect\n[system_default_sect]\nMinProtocol = TLSv1\nCipherString = DEFAULT:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA" >> /etc/ssl/openssl.cnf
RUN sed -i 's/DEFAULT@SECLEVEL=2/DEFAULT@SECLEVEL=1/g' /etc/ssl/openssl.cnf

ENTRYPOINT ["dotnet", "claim.dll"]
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <!-- <TargetFramework>net5.0</TargetFramework> -->
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Dapper" Version="2.0.78" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
    <!-- <PackageReference Include="System.Data.SqlClient" Version="4.6.0" /> -->
    <PackageReference Include="System.Data.SqlClient" Version="4.8.2" />
  </ItemGroup>

</Project>

My conenction String

"Server=10.192.32.197,1521;Database=Claim;User Id=api;Password=kpisystem;Trusted_Connection=False;TrustServerCertificate=False;Encrypt=False;Integrated Security=False";

Error

Exception System.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 31 - Encryption(ssl/tls) handshake failed)
 ---> System.IO.EndOfStreamException: End of stream reached
   at System.Data.SqlClient.SNI.SslOverTdsStream.ReadInternal(Byte[] buffer, Int32 offset, Int32 count, CancellationToken token, Boolean async)
   at System.Data.SqlClient.SNI.SslOverTdsStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at System.Net.FixedSizeReader.ReadPacket(Stream transport, Byte[] buffer, Int32 offset, Int32 count)
   at System.Net.Security.SslStream.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslStream.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslStream.ProcessAuthentication(LazyAsyncResult lazyResult, CancellationToken cancellationToken)
   at System.Net.Security.SslStream.AuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions)
   at System.Net.Security.SslStream.AuthenticateAsClient(String targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, Boolean checkCertificateRevocation)
   at System.Net.Security.SslStream.AuthenticateAsClient(String targetHost)
   at System.Data.SqlClient.SNI.SNITCPHandle.EnableSsl(UInt32 options)
   at System.Data.SqlClient.SNI.SNIProxy.EnableSsl(SNIHandle handle, UInt32 options)
   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken)     
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)  
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at Dapper.SqlMapper.QueryImpl[T](IDbConnection cnn, CommandDefinition command, Type effectiveType)+MoveNext() in /_/Dapper/SqlMapper.cs:line 1083
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in /_/Dapper/SqlMapper.cs:line 725

@Leonardo-Ferreira
Copy link

can you get your hands on a newer version of SQL Server? test connection to one in azure (open a free account) and let me know if the problem persists

@wdrdres3qew5ts21
Copy link

Our system is still using SQL Server 2008 R2 so with this unfortunate circumstance I need to using it in on-premise solutions.

@catinodeh
Copy link

Maybe a little bit related to the topic and since this is a fresh post, I decided to give it a try...

I'm having this exact same issue:

https://serverfault.com/questions/1022414/azure-web-app-suddenly-stops-communicating-with-external-sql-server?newreg=f5d5e5722a43486e92f6efa49d8096e6

We also have SQL Server 2008 R2 and the connection is made directly through our external IP address (we specified our Web App public IPs to have access from outside). The thing is...after some heavy load on our API, it simply starts to log the following error:

2021-04-29 08:10:42.2752|ERROR|WRE.Routing.API.Startup|[POST] https://XXXXXXXX.azurewebsites.net/routes/start Microsoft.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) ---> System.ComponentModel.Win32Exception (5): Access is denied. at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry, SqlConnectionOverrides overrides) at Microsoft.Data.SqlClient.SqlConnection.OpenAsync(CancellationToken cancellationToken) --- End of stack trace from previous location --- at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected) at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable1.AsyncEnumerator.InitializeReaderAsync(DbContext _, Boolean result, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func4 operation, Func4 verifySucceeded, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable1.AsyncEnumerator.MoveNextAsync() at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable1 asyncEnumerable, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable1 asyncEnumerable, CancellationToken cancellationToken) at WRE.Routing.Business.Services.RouteService.GetSamsaraTruckId(String vehicleId) in D:\a\1\s\WRE.Routing.Business\Services\RouteService.cs:line 114 at WRE.Routing.Business.Services.RouteService.ProcessEventByRoutingService(String vehicleId, Int32 employeeId, String orderId, DateTime eventDateTime, ERouteEvent eventType) in D:\a\1\s\WRE.Routing.Business\Services\RouteService.cs:line 93 at WRE.Routing.Business.Services.RouteService.RouteStarted(String vehicleId, Int32 employeeId, DateTime eventDateTime) in D:\a\1\s\WRE.Routing.Business\Services\RouteService.cs:line 41 at WRE.Routing.API.Controllers.RoutesController.HandleRouteStarted(RouteEventViewModel model) in D:\a\1\s\WRE.Routing.API\Controllers\RoutesController.cs:line 27 at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Logged|12_1(ControllerActionInvoker invoker) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker) at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext) at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider) at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task) ClientConnectionId:00000000-0000-0000-0000-000000000000 Error Number:5,State:0,Class:20

The error goes away if we don't do anything and I noticed that if I restart the Web App, it also fixes the issue.

Any thoughts?

@halfs2
Copy link

halfs2 commented Feb 3, 2022

@charlienilsson tks for the article, but the error persists... I have tried several combinations... even using other images such as 5.0-focal-amd64... the iteration process between tests is quite slow for me cause I can only reproduce on QA env. Ironically the DEV database is TLSv1.2 enabled... to be precise I tested:

MinProtocol = TLSv1
CipherString = ECDHE-ECDSA-bla bla bla

MinProtocol = TLSv1
CipherString = DEFAULT@SECLEVEL=1

using both images 5.0 and 5.0-focal-amd64

I was with the same problem A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 31 - Encryption(ssl/tls) handshake failed)

I manage to work with 5.0-buster-slim and including only this changes in dockerfile:

RUN sed -i 's/DEFAULT@SECLEVEL=2/ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256/g' /etc/ssl/openssl.cnf
RUN sed -i 's/DEFAULT@SECLEVEL=2/ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256/g' /usr/lib/ssl/openssl.cnf

worked for me, net 5 console application, running on aws fargate
i add command before last entrypoint in final layer

FROM base AS final

WORKDIR /app

COPY --from=publish /app/publish .

RUN sed -i 's/DEFAULT@SECLEVEL=2/ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256/g' /etc/ssl/openssl.cnf

ENTRYPOINT ["dotnet", "app.dll"]

thanks

@MUhammadasadnazar
Copy link

Hi @machoubie ,

From the docker info, it's hard to tell what SQL server version you are using. Could you provide more information about your server? And what docker images you are using? Is the Ubuntu 18.04 OS the actual system or the docker container you are using to connect to the server?

I assume that you are using the Microsoft.Data.SqlClient v2.0.0 because you have seen the "End of stream reached" error message which is recently introduced by PR 577. This error may be related to Server certificate force encryption #609 or lower TLS version used by the server (quote from 201).

You can check the following settings first on your side:

  1. Check if the SQL Server has Force Encryption as YES.
  2. If yes, add Trust Server Certificate = true in your connection string or Set Force Encryption to NO.

If the above two steps don't solve your issue, you may face a similar case when your server is using lower version of TLS. If possible, you can try to write a simple .NET core application to connect to your target server and see if you get warning message like Security Warning: The negotiated TLS1.0 is an insecure protocol and is supported for backward compatibility only. The recommended protocol version is TLS 1.2 and later. If you see such warning, either your server or your client environment is using lower TLS version to communicate with the other.

Hi dear , i am facing same issue in .Net Maui project can you please help me , I am Stuck from the last Two Days .

@inlineHamed
Copy link

inlineHamed commented Aug 7, 2022

On mcr.microsoft.com/dotnet/aspnet:6.0 docker image, this worked for me:

RUN sed -i 's/MinProtocol = TLSv1.2/MinProtocol = TLSv1/g' /etc/ssl/openssl.cnf
RUN sed -i 's/CipherString = DEFAULT@SECLEVEL=2/CipherString = DEFAULT@SECLEVEL=1/g' /etc/ssl/openssl.cnf

@sayago69
Copy link

sayago69 commented Nov 7, 2022

Hello,

We are suffering from the same error message when our API is trying to access the database:

Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 31 - Encryption(ssl/tls) handshake failed)

In our case, the API is made with .NET 6 and hosted in a Linux container while the SQL Server is a SQL Server 2016 (SP3) running in a Windows Server 2012 R2 with .NET Framework 4.8 installed. We assume this all means that no additional software/updates are needed for enabling TLS1.2 in that server.

Regarding the configuration, SQL Server is NOT configured to Force Encryption while the server's registry is set as follows:

  • HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Client:
    DisableByDefault = 0x00000001
    Enabled = 0xffffffff

  • HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Server:
    DisableByDefault = 0x00000001
    Enabled = 0x00000000

  • HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client:
    DisableByDefault = 0x00000000
    Enabled = 0xffffffff

  • HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server:
    DisableByDefault = 0x00000000
    Enabled = 0xffffffff

  • HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client:
    DisableByDefault = 0x00000000
    Enabled = 0xffffffff

  • HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server:
    DisableByDefault = 0x00000000
    Enabled = 0xffffffff

Last but not least, this is how our current connection string looks like:

Server=myDatabaseServerUrl;Database=MyDatabase;User Id=sa;Password=mysecurepassword;

We have also tried the same connection string with Trust Server Certificate=true; appended and no one works.

We have been researching not only in this thread but in some other articles across the Internet and nothing is solving this issue.

The "funny" thing is that we have been using WireShark to check the connections to the database and, every time we try to connect from a Linux container (either AKS or Docker), the hand-shaking seems to be using TLS1.0. On the other hand, if we run the API from Visual Studio on Windows against the same server, it works perfectly using TLS1.2.

In addition, we have another server with a pretty similar configuration where the container app is working fine but it's using Windows Server 2019 and SQL Server 2019, so we wonder what might be different between those server and database versions.

Since this newer server is working fine without forcing the encryption for SQL Server, we have assumed that's not the problem. We have tested turning it on though with unsuccessful results.

We have also tested the container configuration, just in case. It's using a mcr.microsoft.com/dotnet/aspnet:6.0 docker image and the openssl.cnf file is configured as follows:

[system_default_sect] MinProtocol = TLSv1.2 CipherString = DEFAULT@SECLEVEL=2

Of course, we've tried some other configurations such as the ones mentioned above in this thread, but nothing worked.

Does anyone have any idea, suggestion or comment that might put us in the right direction to solve this issue?

Thank you in advance!

P.S: upgrading the server to either Windows Server 2019 and/or SQL Server 2019 is, unfortunately, not an option.

@JRahnama
Copy link
Contributor

JRahnama commented Nov 8, 2022

@sayago69 have you tried adding Encrypt = false to your connection string?

@sayago69
Copy link

sayago69 commented Nov 9, 2022

Yes, we have tried with both Encrypt=false and Encrypt=true and still not working. It keeps using TLS 1.0.

However, I think we have managed to find a solution: we have added this bit RUN sed -i 's/TLSv1.2/TLSv1.0/g' /etc/ssl/openssl.cnf to the docker file, but not at the end but just at the beginning just after the Expose clauses:

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 8080
EXPOSE 443
RUN sed -i 's/TLSv1.2/TLSv1.0/g' /etc/ssl/openssl.cnf

After adding that line, we started getting a slightly different error:

Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: TCP Provider, error: 35 - An internal exception was caught)
---> System.Security.Authentication.AuthenticationException: The remote certificate was rejected by the provided RemoteCertificateValidationCallback.

Then, we made it work just by adding Trust Server Certificate=true; to our connecting string:

Server=myDatabaseServerUrl;Database=MyDatabase;User Id=sa;Password=mysecurepassword;Trust Server Certificate=true;

Hope it might help someone else.

@felopezm
Copy link

felopezm commented Nov 9, 2022

@sayago69 Your answer worked for me, additionally add the 'Encrypt=False' in the connection string. Thank you

@sayago69
Copy link

sayago69 commented Nov 9, 2022

@sayago69 Your answer worked for me, additionally add the 'Encrypt=False' in the connection string. Thank you

You're welcome.

Unfortunately, that solution fixed our API's connection to SQL Server but broke our API's connection to RabbitMQ which only accepts TLS1.2 as far as I'm aware.

Still trying to understand why changing the minimum protocol in openssl.cnf to 1.0 is making it work if both the API and SQL Server are eventually handshaking using TLS 1.2. Why didn't they do it before when the minimum protocol was TLS1.2? We must have changed something else in that file.

Anyway, we'll keep investigating...

@sayago69
Copy link

Well, it seems we have finally managed to figure out a lasting solution to this problem. We just added the following line to our docker file just after the EXPOSE lines:

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 8080
EXPOSE 443
RUN sed -i 's/CipherString = DEFAULT@SECLEVEL=2/CipherString = DEFAULT@SECLEVEL=1/g' /etc/ssl/openssl.cnf

Note that this is just one of the lines suggested by @inlineHamed earlier but in a different place in the docker file. We started adding those two lines (and worked) but we figured out that the second line was enough. It didn't work fine with only the first line.

Also, our connection to the database doesn't need Trust Server Certificate=true anymore.

Once again, hope this may help someone else.

@LaXiS96
Copy link

LaXiS96 commented Feb 15, 2023

As of today, the aspnet:6.0 Docker image has this weird behaviour: setting MinProtocol to TLSv1.0 (which was working on aspnet:3.1) results in an exception similar to the original post, but simply changing the value to TLSv1 instead fixes the issue.
CipherString still needs to be set to DEFAULT@SECLEVEL=1.

@GaTechThomas
Copy link

I was having the same problem and this issue thread helped me to solve it. Simply adding the following to the connection string solved it:

;TrustServerCertificate=true

@garrettsutula
Copy link

garrettsutula commented Dec 13, 2023

As of today, the aspnet:6.0 Docker image has this weird behaviour: setting MinProtocol to TLSv1.0 (which was working on aspnet:3.1) results in an exception similar to the original post, but simply changing the value to TLSv1 instead fixes the issue. CipherString still needs to be set to DEFAULT@SECLEVEL=1.

Thanks, this saved me a bunch of time today but the configuration blocks for this aren't present in latest /etc/ssl/openssl.cnf in the MS container images I am working with so I followed this guide on how to set up the right config objects to pass min protocol and cipher string settings.

@Mehranh
Copy link

Mehranh commented Dec 15, 2023

Unfortunately that does not solve for .Net 8

On mcr.microsoft.com/dotnet/aspnet:6.0 docker image, this worked for me:

RUN sed -i 's/MinProtocol = TLSv1.2/MinProtocol = TLSv1/g' /etc/ssl/openssl.cnf
RUN sed -i 's/CipherString = DEFAULT@SECLEVEL=2/CipherString = DEFAULT@SECLEVEL=1/g' /etc/ssl/openssl.cnf

@amingolmahalle
Copy link

@Mehranh please visit the link below:
https://github.com/dotnet/SqlClient/issues/2252#issuecomment-1872966588

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests