Provider tcp provider error 35 an internal exception was caught

Azure Data Studio Version: 1.37.0 OS Version: macOS Catalina 10.15.7 Steps to Reproduce: Open ADS Log into VPN Connect to any managed instance in our production subscription "TCP Provider, err...

Cheena,
Thanks — I had a few minutes between some extensive travel this week and gave it a whirl but my Mac did not like that install attempt. The error is below. I don’t have time to dig into this afternoon since I’m getting on an airplane but any guidance you have here is much appreciated. I do appreciate the help very much. 
Matt Gordon

Searching for pip

Reading https://pypi.org/simple/pip/

Downloading https://files.pythonhosted.org/packages/4b/30/e15b806597e67057e07a5acdc135216ccbf76a5f1681a324533b61066b0b/pip-22.2.2.tar.gz#sha256=3fd1929db052f056d7a998439176d3333fa1b3f6c1ad881de1885c0717608a4b

Best match: pip 22.2.2

Processing pip-22.2.2.tar.gz

Writing /tmp/easy_install-9hgzSx/pip-22.2.2/setup.cfg

Running pip-22.2.2/setup.py -q bdist_egg —dist-dir /tmp/easy_install-9hgzSx/pip-22.2.2/egg-dist-tmp-xxfS3t

Traceback (most recent call last):

  File «/usr/bin/easy_install», line 13, in <module>

    load_entry_point(‘setuptools==41.0.1’, ‘console_scripts’, ‘easy_install’)()

  File «/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/command/easy_install.py», line 2316, in main

    **kw

  File «/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/__init__.py», line 145, in setup

    return distutils.core.setup(**attrs)

  File «/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/core.py», line 151, in setup

    dist.run_commands()

  File «/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py», line 953, in run_commands

    self.run_command(cmd)

  File «/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py», line 972, in run_command

    cmd_obj.run()

  File «/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/command/easy_install.py», line 418, in run

    self.easy_install(spec, not self.no_deps)

  File «/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/command/easy_install.py», line 679, in easy_install

    return self.install_item(spec, dist.location, tmpdir, deps)

  File «/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/command/easy_install.py», line 705, in install_item

    dists = self.install_eggs(spec, download, tmpdir)

  File «/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/command/easy_install.py», line 890, in install_eggs

    return self.build_and_install(setup_script, setup_base)

  File «/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/command/easy_install.py», line 1158, in build_and_install

    self.run_setup(setup_script, setup_base, args)

  File «/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/command/easy_install.py», line 1144, in run_setup

    run_setup(setup_script, args)

  File «/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/sandbox.py», line 253, in run_setup

    raise

  File «/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py», line 35, in __exit__

    self.gen.throw(type, value, traceback)

  File «/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/sandbox.py», line 195, in setup_context

    yield

  File «/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py», line 35, in __exit__

    self.gen.throw(type, value, traceback)

  File «/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/sandbox.py», line 166, in save_modules

    saved_exc.resume()

  File «/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/sandbox.py», line 141, in resume

    six.reraise(type, exc, self._tb)

  File «/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/sandbox.py», line 154, in save_modules

    yield saved

  File «/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/sandbox.py», line 195, in setup_context

    yield

  File «/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/sandbox.py», line 250, in run_setup

    _execfile(setup_script, ns)

  File «/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/sandbox.py», line 44, in _execfile

    code = compile(script, filename, ‘exec’)

  File «/tmp/easy_install-9hgzSx/pip-22.2.2/setup.py», line 7

    def read(rel_path: str) -> str:

                     ^

SyntaxError: invalid syntax

On Wednesday, August 24, 2022 at 01:44:47 PM EDT, Cheena Malhotra ***@***.***> wrote:

Could you try installing mssql-cli first: https://github.com/dbcli/mssql-cli/blob/main/doc/installation/macos.md


Reply to this email directly, view it on GitHub, or unsubscribe.
You are receiving this because you were mentioned.Message ID: ***@***.***>

Содержание

  1. SqlClient troubleshooting guide
  2. Exceptions when connecting to SQL Server
  3. Unable to load native SNI (Server Name Indication) library
  4. Issues in .NET Framework applications
  5. Issues in .NET Core applications
  6. Native SNI (pdb not found) errors
  7. Hostname resolution errors
  8. Possible reasons
  9. Login-phase errors
  10. Possible reasons and solutions
  11. Connection Pool exhaustion errors
  12. Possible reasons and solutions
  13. Contact Support
  14. Руководство по устранению неполадок с SqlClient
  15. Исключения при подключении к SQL Server
  16. Не удалось загрузить нативную библиотеку SNI (указание имени сервера)
  17. Проблемы в приложениях .NET Framework
  18. Проблемы в приложениях .NET Core
  19. Ошибки нативной функции SNI (не удалось найти PDB)
  20. Ошибки разрешения имени узла
  21. Возможные причины
  22. Ошибки на этапе входа
  23. Возможные причины и решения
  24. Проблема, вызванная тем, что пул подключений исчерпан
  25. Возможные причины и решения
  26. Обращение в службу поддержки
  27. 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) #6452
  28. Comments

SqlClient troubleshooting guide

Download ADO.NET

Exceptions when connecting to SQL Server

There are various reasons why connection can fail to be established. Below are some troubleshooting tips that can be used as a guide to analyze and solve many of the problems.

Unable to load native SNI (Server Name Indication) library

Issues in .NET Framework applications

SNI is the native C++ library that SqlClient depends on for various network operations when running on Windows. In .NET Framework applications that are built with the MSBuild Project SDK, native DLLs aren’t managed with restore commands. So a «.targets» file is included in the «Microsoft.Data.SqlClient.SNI» NuGet package that defines the necessary «Copy» operations.

The included «.targets» file is auto-referenced when a direct dependency is made to the «Microsoft.Data.SqlClient» library. In scenarios where a transitive (indirect) reference is made, this «.targets» file should be manually referenced to ensure «Copy» operations can execute when necessary.

Recommended Solution: Make sure the «.targets» file is referenced in the application’s «.csproj» file to ensure «Copy» operations are executed.

These targets cover Microsoft’s well-known and commonly used targets only. If an external tool or application defines custom targets to copy binaries, new targets must be defined by tool maintainers to ensure native SNI DLLs are copied along-side the Microsoft.Data.SqlClient.dll binaries and are available when executing client applications.

Issues in .NET Core applications

This error may occur on Windows applications only. If it occurs in a Unix environment, you must ensure your application is built to appropriately target a Unix runtime and not for Windows.

SNI is the native C++ library that SqlClient depends on for various network operations when running on Windows. Microsoft.Data.SqlClient doesn’t manage loading/unloading of this library in .NET Core.

Recommended Solution: Ensure «Execute» permissions are granted on the filesystem where native runtime libraries are loaded in the .NET Core process. If that doesn’t solve the issue, you can file an issue in the dotnet/runtime repository for further support.

Native SNI (pdb not found) errors

Recommended Solution: Ensure client application references minimum v2.1.0 version of Microsoft.Data.SqlClient package. When using EF Core, add a reference to this package version of Microsoft.Data.SqlClient directly to override dependency.

Hostname resolution errors

Possible reasons

TCP/Named Pipes Protocol isn’t enabled on SQL Server

Recommended Solution: Enable the TCP/Named Pipes Protocol on the SQL Server instance from the SQL Server Configuration Manager console.

Hostname not known

Recommended Solution: Ensure the hostname resolves to the Server’s IP address from the client where the connection is being initiated.

Login-phase errors

Possible reasons and solutions

SQL Server doesn’t support TLS 1.2

This error typically occurs in client environments like docker image containers, Unix clients, or Windows clients where TLS 1.2 is the minimum supported TLS protocol.

Recommended Solution: Install the latest updates on supported versions of SQL Server 1 and ensure the TLS 1.2 protocol is enabled on the server.

1 View SqlClient driver support lifecycle for the list of supported SQL Server versions with different versions of Microsoft.Data.SqlClient.

Insecure solution: Configure TLS/SSL settings in the docker image/client environment to connect with TLS 1.0.

When connecting with Microsoft.Data.SqlClient v2.0+ from a Windows/Linux environment with TLS 1.0 or TLS 1.1, a security warning message will be thrown if the target SQL Server and client cannot negotiate a minimum of TLS version 1.2 when establishing the connection: Security Warning: The negotiated is an insecure protocol and is supported for backward compatibility only. The recommended protocol version is TLS 1.2 and later.

SQL Server enforced encryption

If the target Server is an Azure SQL instance or an on-premises SQL Server with the «Force Encryption» property turned on, an encrypted connection will be made, for which the client must establish trust with the server.

Recommended Solution: There are two available options to fix this issue:

  1. Install the target SQL Server’s TLS/SSL certificate in the client environment. It will be validated if encryption is needed.
  2. Set the «TrustServerCertificate=true» property in the connection string.

Insecure solution: Disable the «Force Encryption» setting on SQL Server.

TLS/SSL Certificates not signed with SHA-256 or above.

Recommended Solution: Generate a new TLS/SSL Certificate for the server whose hash is signed with at-least the SHA-256 hashing algorithm.

Tightly restricted cipher suites on Linux with .NET 5+

.NET 5 introduced a breaking change for Linux clients, where a tightly restricted list of permitted cipher suites is used by default. You may need to expand the default cipher suite list to accept legacy clients (or to contact legacy servers) by either specify a CipherSuitePolicy value or changing the OpenSSL configuration file.

Connection Pool exhaustion errors

Possible reasons and solutions

Client application is opening more connections than the connection pool can hold active at a given time.

Recommended Solution: Configure «Max Pool Size» connection property to a higher value and close unused connections in timely manner.

If this guide doesn’t solve your connectivity issues, you may view existing issues in the dotnet/sqlclient repository and open a new issue if needed.

Источник

Руководство по устранению неполадок с SqlClient

Скачать ADO.NET

Исключения при подключении к SQL Server

Есть несколько причин, по которым не удается установить подключение. Ниже приведено несколько советов по устранению неполадок. Эти советы можно использовать для анализа и решения многих проблем.

Не удалось загрузить нативную библиотеку SNI (указание имени сервера)

Проблемы в приложениях .NET Framework

Отслеживаемая трассировка стека:

SNI — это нативная библиотека C++, на основе которой в SqlClient выполняются различные сетевые операции при работе в Windows. В приложениях .NET Framework, созданных с помощью пакета SDK для проекта MSBuild, управление нативными библиотеками DLL не осуществляется с помощью команд восстановления. Таким образом, файл .targets включается в пакет NuGet Microsoft.Data.SqlClient.SNI, который определяет необходимые операции копирования.

Для включаемого файла .targets при установке прямой зависимости от библиотеки Microsoft.Data.SqlClient создается автоматическая ссылка. В сценариях, где создается транзитная (косвенная) ссылка, необходимо вручную ссылаться на этот файл .targets, чтобы при необходимости могли выполняться операции копирования.

Рекомендуемое решение. Убедитесь, что в файле .csproj приложения есть ссылка на файл .targets, чтобы обеспечить выполнение операций копирования.

Среди этих целевых объектов только известные и часто используемые целевые объекты Майкрософт. Если внешний инструмент или приложение определяет пользовательские целевые объекты для копирования двоичных файлов, то средства обслуживания инструмента должны определить новые целевые объекты, чтобы обеспечить копирование нативных DLL-библиотек SNI вместе с двоичными файлами Microsoft.Data.SqlClient.dll и доступность таких библиотек при выполнении клиентских приложений.

Проблемы в приложениях .NET Core

Отслеживаемая трассировка стека:

Эта ошибка может возникать только в Windows-приложениях. Если это происходит в среде Unix, убедитесь, что приложение создано для среды выполнения UNIX, а не для Windows.

SNI — это нативная библиотека C++, на основе которой в SqlClient выполняются различные сетевые операции при работе в Windows. Microsoft.Data.SqlClient не управляет загрузкой этой библиотеки в ПО .NET Core и ее выгрузкой из него.

Рекомендуемое решение. Обеспечьте для файловой системы, где нативные библиотеки среды выполнения загружаются в процесс .NET Core, разрешения на выполнение. Если это не помогло решить проблему, можно зарегистрировать ее в репозитории dotnet/runtime, чтобы получить дальнейшую поддержку.

Ошибки нативной функции SNI (не удалось найти PDB)

Отслеживаемая трассировка стека:

Рекомендуемое решение. Убедитесь, что клиентское приложение ссылается на минимальную версию 2.1.0 пакета Microsoft.Data.SqlClient. При использовании EF Core добавьте ссылку на эту версию пакета Microsoft.Data.SqlClient напрямую, чтобы переопределить зависимость.

Ошибки разрешения имени узла

Отслеживаемая трассировка стека:

Возможные причины

В SQL Server не включен протокол TCP или протокол именованных каналов

Рекомендуемое решение. Включите протокол TCP или протокол именованных каналов в экземпляре SQL Server из консоли диспетчера конфигурации SQL Server.

Имя узла неизвестно

Рекомендуемое решение. Убедитесь, что имя узла разрешается в IP-адрес сервера от клиента, в котором инициируется подключение.

Ошибки на этапе входа

Отслеживаемые трассировки стека:

Возможные причины и решения

SQL Server не поддерживает TLS 1.2

Эта ошибка обычно происходит в клиентских средах, таких как контейнеры образов Docker, клиенты Unix или клиенты Windows, где TLS 1.2 является минимальной поддерживаемой версией протокола TLS.

Рекомендуемое решение. Установите последние обновления для поддерживаемых версий SQL Server 1 и убедитесь, что на сервере включен протокол TLS 1.2.

1 Список поддерживаемых версий SQL Server с разными версиями Microsoft.Data.SqlClient см. в статье Жизненный цикл поддержки драйвера SqlClient.

Небезопасное решение. Настройте параметры TLS/SSL в среде образа или клиента Docker для подключения к TLS 1.0.

При подключении к Microsoft.Data.SqlClient версии 2.0 и выше из среды Windows или Linux с использованием TLS 1.0 или TLS 1.1 будет активировано предупреждение системы безопасности, если целевому объекту SQL Server и клиенту не удается согласовать минимальную версию TLS 1.2 при установке соединения: Security Warning: The negotiated is an insecure protocol and is supported for backward compatibility only. The recommended protocol version is TLS 1.2 and later.

Принудительное шифрование SQL Server

Если целевой сервер является экземпляром Azure SQL или локальной SQL Server с включенным свойством «Принудительное шифрование», будет установлено зашифрованное подключение, для которого клиент должен установить доверие с сервером.

Рекомендуемое решение. Есть два варианта устранения этой проблемы:

  1. Установите сертификат TLS/SSL для целевого экземпляра SQL Server в клиентской среде. Будет выполнена проверка на предмет того, нужно ли шифрование.
  2. Задайте свойство TrustServerCertificate=true в строке подключения.

Небезопасное решение. Отключите параметр принудительного шифрования в SQL Server.

Сертификаты TLS/SSL не подписаны с помощью SHA-256 или более поздней версии.

Рекомендуемое решение. Создайте новый сертификат TLS/SSL для сервера, хэш которого подписывается по меньшей мере с помощью алгоритма хэширования SHA-256.

Строго ограниченный список комплектов шифров TLS для .NET 5 и более поздних версий в Linux

В .NET 5 представлено критическое изменение для клиентов Linux, которое заключается в использовании строго ограниченного списка разрешенных комплектов шифров по умолчанию. Если необходимо расширить список комплектов шифров по умолчанию для работы с устаревшими клиентами (или для взаимодействия с устаревшими серверами), укажите значение CipherSuitePolicy или измените файл конфигурации OpenSSL.

Дополнительные сведения о рекомендуемых действиях см. в статье Комплекты шифров TLS по умолчанию для .NET в Linux.

Проблема, вызванная тем, что пул подключений исчерпан

Отслеживаемая трассировка стека:

Возможные причины и решения

Клиентское приложение открывает больше подключений, чем пул соединений может сохранить в текущий момент.

Рекомендуемое решение. Задайте для свойства соединения Max Pool Size большее значение и своевременно закрывайте неиспользуемые подключения.

Обращение в службу поддержки

Если это не помогло устранить проблемы с подключением, вы можете просмотреть сведения о существующих проблемах в репозитории dotnet/sqlclient и при необходимости открыть новую проблему.

Источник

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) #6452

Azure Data Studio Version: 1.9.0

I only found 1 other issue that seemed the same as this but it was closed with reference to a stackExchange page that did not help.

I am able to ping the server in question and am able to connect to it via MSSMS on windows 10.

The MSSQL Server in question is running on MSSQL 2012

The developer console on Azure Data Studio doesn’t give any helpful logging.
( just «added connection» — fails — «removed connection» )

I am running on Solus Linux (latest as of last week.)

Please tell me if there’s anything more i can provide to be more helpful.

EDIT: Tested on insiders build today and gives the same issue.

See copied logging below:

System.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: Authentication failed, see inner exception. —> System.TypeInitializationException: The type initializer for ‘SslMethods’ threw an exception. —> System.TypeInitializationException: The type initializer for ‘Ssl’ threw an exception. —> System.TypeInitializationException: The type initializer for ‘SslInitializer’ threw an exception. —> Interop+Crypto+OpenSslCryptographicException: error:25070067:DSO support routines:DSO_load:could not load the shared library
at Interop.SslInitializer..cctor()
— End of inner exception stack trace —
at Interop.Ssl..cctor()
— End of inner exception stack trace —
at Interop.Ssl.SslV2_3Method()
at Interop.Ssl.SslMethods..cctor()
— End of inner exception stack trace —
at Interop.OpenSsl.AllocateSslContext(SslProtocols protocols, SafeX509Handle certHandle, SafeEvpPKeyHandle certKeyHandle, EncryptionPolicy policy, SslAuthenticationOptions sslAuthenticationOptions)
at System.Net.Security.SafeDeleteSslContext..ctor(SafeFreeSslCredentials credential, SslAuthenticationOptions sslAuthenticationOptions)
at System.Net.Security.SslStreamPal.HandshakeInternal(SafeFreeCredentials credential, SafeDeleteContext& context, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, SslAuthenticationOptions sslAuthenticationOptions)
— End of inner exception stack trace —
at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo exception)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
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.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.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.<>c__DisplayClass40_0.b__1(Task 1 _) at System.Threading.Tasks.ContinuationResultTaskFromResultTask 2.InnerInvoke()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
— End of stack trace from previous location where exception was thrown —
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
— End of stack trace from previous location where exception was thrown —
at Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection.ReliableSqlConnection.<>c__DisplayClass28_0. d.MoveNext() in D:a1ssrcMicrosoft.SqlTools.ManagedBatchParserReliableConnectionReliableSqlConnection.cs:line 303
— End of stack trace from previous location where exception was thrown —
at Microsoft.SqlTools.ServiceLayer.Connection.ConnectionService.TryOpenConnection(ConnectionInfo connectionInfo, ConnectParams connectionParams) in D:a1ssrcMicrosoft.SqlTools.ServiceLayerConnectionConnectionService.cs:line 521
ClientConnectionId:1b001fa5-02ab-49db-857d-1d7ba62bb371

Azure Data Studio version: azuredatastudio 1.9.0 (78a42e1, 2019-07-10T04:10:29.206Z)
OS version: Linux x64 5.1.14-121.current

The text was updated successfully, but these errors were encountered:

Источник

I wonder if you have accessed the MS SQL Server database in the Docker of. NET Core/.NET 5. If so, you are likely to encounter this error.

1 SSL version error

Recently, some business services were reconstructed with. NET 5 in the company. Because the old system used MS SQL Server database before, this reconstruction also decided to continue to use it. However, when deploying the. NET 5 Application to Docker and passing the Swagger test, the following error is reported:

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: Authentication failed, see inner exception.
 ---> Interop+OpenSsl+SslException: SSL Handshake failed with OpenSSL error - SSL_ERROR_SSL.

From the literal meaning, I can’t see what it is. I can only locate this sentence_ ERROR_ SSL. After searching, it is found that the minimum protocol version of OpenSSL in the container image of. NET Core/.NET 5 is TLSv1.2, while the version of our MS SQL Server is lower and does not support TLSv1.2, only TLSv1.

We can go inside the container to verify:

# docker exec -it <docker-name> /bin/bash
# cat /etc/ssl/openssl.cnf

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

Therefore, to clarify the problem, change it directly inside the container: change TLSv1.2 to TLSv1

# docker exec -it <docker-name> /bin/bash
# vi /etc/ssl/openssl.cnf

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

After the change is completed, access the interface again, and no error will be reported.

2. Modify Dockerfile

The above method is only a temporary scheme. Re mirroring will restore TLSv1.2. Therefore, we need to change the Dockerfile to TLSv1 in the source image.

Here, take a simple Dockerfile as an example. You only need to add a line of instructions in the Microsoft. NET 5 image source layer:

RUN sed -i 's/TLSv1.2/TLSv1/g' /etc/ssl/openssl.cnf

Complete Dockerfile example:

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

FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /src
COPY ["AuthCenter.API/AuthCenter.API.csproj", "AuthCenter.API/"]
RUN dotnet restore "AuthCenter.API/AuthCenter.API.csproj"
COPY . .
WORKDIR "/src/AuthCenter.API"
RUN dotnet build "AuthCenter.API.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "AuthCenter.API.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "AuthCenter.API.dll"]

Other associated OpenSSL errors:

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

This error is similar to the above error: 35. The TLS protocol version is higher and SQL Server does not support it. The modification method is also changed to TLSv1. It should be noted that many articles on the Internet suggest changing to TLSv1.0, that is, the following instructions:

RUN sed -i 's/TLSv1.2/TLSv1.0/g' /etc/ssl/openssl.cnf

For most children’s shoes on the Internet, the above sentence is applicable, but there are some like me, even if the above sentence is used. A search found that it needs to be changed to TLSv1 (i.e. remove the decimal point) to work.

3 about TLS protocol

TLS is a network security scheme implemented above TCP transport layer and below application layer. It belongs to application layer protocol in TCP/IP four layer network model. TLS protocol provides data confidentiality and data integrity between two communication applications. In addition, it also provides a connection identity reliability scheme.

UDP uses DTLS protocol to realize secure transmission, which is similar to TLS protocol.

The design purpose of TLS protocol is as follows:

(1) Encryption security: TLS is used to establish a secure connection between both parties and ensure information security through encryption, signature and data summary.

(2) Interoperability: programmers can achieve interoperability without knowing the TLS protocol, as long as the peer code complies with the RFC standard.

(3) Scalability: when necessary, new public key and secret methods can be added through the extension mechanism to avoid creating new protocols.

(4) Relative efficiency: encryption requires a lot of CPU, especially public key operation. After the handshake of TLS protocol is completed, the data is encrypted by symmetric key. TLS also integrates a session caching scheme to reduce the need to establish a connection from scratch.

The location of TLS protocol is as follows:

More about TLS protocol: Click here to read

4 Summary

On the premise of higher and higher security requirements, TLSv1.2 is widely used. In order to adapt to the low version of MS SQL Server, you can choose to reduce the minimum version requirements of TLS protocol in Dockefile to solve the problem. However, this is an unsafe method after all. If possible, it is recommended to upgrade the TLS configuration of the server where MS SQL Server is located to support TLSv1.2.

Понравилась статья? Поделить с друзьями:
  • Provider tcp provider error 0 указанное сетевое имя более недоступно
  • Provider tcp provider error 0 превышен таймаут семафора
  • Provider ssl provider error 31 encryption ssl tls handshake failed
  • Provider ssl provider error 0 время ожидания операции истекло
  • Provider sql network interfaces error 26 ошибка при обнаружении указанного сервера или экземпляра