Ошибка could not create ssl tls secure channel

I finally found the answer (I haven’t noted my source but it was from a search);

While the code works in Windows XP, in Windows 7, you must add this at the beginning:

// using System.Net;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// Use SecurityProtocolType.Ssl3 if needed for compatibility reasons

And now, it works perfectly.


ADDENDUM

As mentioned by Robin French; if you are getting this problem while configuring PayPal, please note that they won’t support SSL3 starting by December, 3rd 2018. You’ll need to use TLS. Here’s Paypal page about it.

answered May 25, 2010 at 13:18

Simon Dugré's user avatar

Simon DugréSimon Dugré

17.7k11 gold badges56 silver badges73 bronze badges

26

The solution to this, in .NET 4.5 is

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

If you don’t have .NET 4.5 then use

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

answered Feb 22, 2018 at 14:46

Andrej Z's user avatar

5

Make sure the ServicePointManager settings are made before the HttpWebRequest is created, else it will not work.

Works:

ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
       | SecurityProtocolType.Tls11
       | SecurityProtocolType.Tls12
       | SecurityProtocolType.Ssl3;

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://google.com/api/")

Fails:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://google.com/api/")

ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
       | SecurityProtocolType.Tls11
       | SecurityProtocolType.Tls12
       | SecurityProtocolType.Ssl3;

soccer7's user avatar

soccer7

3,4193 gold badges29 silver badges49 bronze badges

answered Jun 21, 2018 at 21:39

hogarth45's user avatar

hogarth45hogarth45

3,3471 gold badge22 silver badges27 bronze badges

8

Note: Several of the highest voted answers here advise setting ServicePointManager.SecurityProtocol, but Microsoft explicitly advises against doing that. Below, I go into the typical cause of this issue and the best practices for resolving it.

One of the biggest causes of this issue is the active .NET Framework version. The .NET framework runtime version affects which security protocols are enabled by default.

  • In ASP.NET sites, the framework runtime version is often specified in web.config. (see below)
  • In other apps, the runtime version is usually the version for which the project was built, regardless of whether it is running on a machine with a newer .NET version.

There doesn’t seem to be any authoritative documentation on how it specifically works in different versions, but it seems the defaults are determined more or less as follows:

Framework Version Default Protocols
4.5 and earlier SSL 3.0, TLS 1.0
4.6.x TLS 1.0, 1.1, 1.2, 1.3
4.7+ System (OS) Defaults

For the older versions, your mileage may vary somewhat based on which .NET runtimes are installed on the system. For example, there could be a situation where you are using a very old framework and TLS 1.0 is not supported, or using 4.6.x and TLS 1.3 is not supported.

Microsoft’s documentation strongly advises using 4.7+ and the system defaults:

We recommend that you:

  • Target .NET Framework 4.7 or later versions on your apps. Target .NET Framework 4.7.1 or later versions on your WCF apps.
  • Do not specify the TLS version. Configure your code to let the OS decide on the TLS version.
  • Perform a thorough code audit to verify you’re not specifying a TLS or SSL version.

For ASP.NET sites: check the targetFramework version in your <httpRuntime> element, as this (when present) determines which runtime is actually used by your site:

<httpRuntime targetFramework="4.5" />

Better:

<httpRuntime targetFramework="4.7" />

answered Oct 2, 2019 at 6:02

JLRishe's user avatar

JLRisheJLRishe

99k19 gold badges131 silver badges169 bronze badges

6

I had this problem trying to hit https://ct.mob0.com/Styles/Fun.png, which is an image distributed by CloudFlare on its CDN that supports crazy stuff like SPDY and weird redirect SSL certs.

Instead of specifying Ssl3 as in Simons answer I was able to fix it by going down to Tls12 like this:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
new WebClient().DownloadData("https://ct.mob0.com/Styles/Fun.png");

InteXX's user avatar

InteXX

6,0736 gold badges41 silver badges77 bronze badges

answered Oct 15, 2014 at 17:42

Bryan Legend's user avatar

Bryan LegendBryan Legend

6,7601 gold badge59 silver badges60 bronze badges

3

After many long hours with this same issue I found that the ASP.NET account the client service was running under didn’t have access to the certificate. I fixed it by going into the IIS Application Pool that the web app runs under, going into Advanced Settings, and changing the Identity to the LocalSystem account from NetworkService.

A better solution is to get the certificate working with the default NetworkService account but this works for quick functional testing.

answered Dec 4, 2014 at 16:31

Nick Gotch's user avatar

Nick GotchNick Gotch

9,15714 gold badges70 silver badges97 bronze badges

3

The error is generic and there are many reasons why the SSL/TLS negotiation may fail. The most common is an invalid or expired server certificate, and you took care of that by providing your own server certificate validation hook, but is not necessarily the only reason. The server may require mutual authentication, it may be configured with a suites of ciphers not supported by your client, it may have a time drift too big for the handshake to succeed and many more reasons.

The best solution is to use the SChannel troubleshooting tools set. SChannel is the SSPI provider responsible for SSL and TLS and your client will use it for the handshake. Take a look at TLS/SSL Tools and Settings.

Also see How to enable Schannel event logging.

answered May 18, 2010 at 18:14

Remus Rusanu's user avatar

Remus RusanuRemus Rusanu

287k40 gold badges437 silver badges567 bronze badges

3

The approach with setting

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

Seems to be okay, because Tls1.2 is latest version of secure protocol. But I decided to look deeper and answer do we really need to hardcode it.

Specs: Windows Server 2012R2 x64.

From the internet there is told that .NetFramework 4.6+ must use Tls1.2 by default. But when I updated my project to 4.6 nothing happened.
I have found some info that tells I need manually do some changes to enable Tls1.2 by default

https://support.microsoft.com/en-in/help/3140245/update-to-enable-tls-1-1-and-tls-1-2-as-default-secure-protocols-in-wi

But proposed windows update doesnt work for R2 version

But what helped me is adding 2 values to registry. You can use next PS script so they will be added automatically

Set-ItemProperty -Path 'HKLM:SOFTWAREWow6432NodeMicrosoft.NetFrameworkv4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
Set-ItemProperty -Path 'HKLM:SOFTWAREMicrosoft.NetFrameworkv4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord

That is kind of what I was looking for. But still I cant answer on question why NetFramework 4.6+ doesn’t set this …Protocol value automatically?

answered Oct 28, 2019 at 20:58

simply good's user avatar

simply goodsimply good

9711 gold badge12 silver badges26 bronze badges

5

Another possible cause of the The request was aborted: Could not create SSL/TLS secure channel error is a mismatch between your client PC’s configured cipher_suites values, and the values that the server is configured as being willing and able to accept. In this case, when your client sends the list of cipher_suites values that it is able to accept in its initial SSL handshaking/negotiation «Client Hello» message, the server sees that none of the provided values are acceptable, and may return an «Alert» response instead of proceeding to the «Server Hello» step of the SSL handshake.

To investigate this possibility, you can download Microsoft Message Analyzer, and use it to run a trace on the SSL negotiation that occurs when you try and fail to establish an HTTPS connection to the server (in your C# app).

If you are able to make a successful HTTPS connection from another environment (e.g. the Windows XP machine that you mentioned — or possibly by hitting the HTTPS URL in a non-Microsoft browser that doesn’t use the OS’s cipher suite settings, such as Chrome or Firefox), run another Message Analyzer trace in that environment to capture what happens when the SSL negotiation succeeds.

Hopefully, you’ll see some difference between the two Client Hello messages that will allow you to pinpoint exactly what about the failing SSL negotiation is causing it to fail. Then you should be able to make configuration changes to Windows that will allow it to succeed. IISCrypto is a great tool to use for this (even for client PCs, despite the «IIS» name).

The following two Windows registry keys govern the cipher_suites values that your PC will use:

  • HKLMSOFTWAREPoliciesMicrosoftCryptographyConfigurationSSL0010002
  • HKLMSYSTEMCurrentControlSetControlCryptographyConfigurationLocalSSL0010002

Here’s a full writeup of how I investigated and solved an instance of this variety of the Could not create SSL/TLS secure channel problem: http://blog.jonschneider.com/2016/08/fix-ssl-handshaking-error-in-windows.html

answered Aug 31, 2016 at 4:33

Jon Schneider's user avatar

Jon SchneiderJon Schneider

25.5k23 gold badges140 silver badges168 bronze badges

3

Something the original answer didn’t have. I added some more code to make it bullet proof.

ServicePointManager.Expect100Continue = true;
        ServicePointManager.DefaultConnectionLimit = 9999;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;

answered Jun 1, 2016 at 15:05

SpoiledTechie.com's user avatar

SpoiledTechie.comSpoiledTechie.com

10.5k21 gold badges77 silver badges99 bronze badges

5

The top-voted answer will probably be enough for most people. However, in some circumstances, you could continue getting a «Could not create SSL/TLS secure channel» error even after forcing TLS 1.2. If so, you may want to consult this helpful article for additional troubleshooting steps. To summarize: independent of the TLS/SSL version issue, the client and server must agree on a «cipher suite.» During the «handshake» phase of the SSL connection, the client will list its supported cipher-suites for the server to check against its own list. But on some Windows machines, certain common cipher-suites may have been disabled (seemingly due to well-intentioned attempts to limit attack surface), decreasing the possibility of the client & server agreeing on a cipher suite. If they cannot agree, then you may see «fatal alert code 40» in the event viewer and «Could not create SSL/TLS secure channel» in your .NET program.

The aforementioned article explains how to list all of a machine’s potentially-supported cipher suites and enable additional cipher suites through the Windows Registry. To help check which cipher suites are enabled on the client, try visiting this diagnostic page in MSIE. (Using System.Net tracing may give more definitive results.) To check which cipher suites are supported by the server, try this online tool (assuming that the server is Internet-accessible). It should go without saying that Registry edits must be done with caution, especially where networking is involved. (Is your machine a remote-hosted VM? If you were to break networking, would the VM be accessible at all?)

In my company’s case, we enabled several additional «ECDHE_ECDSA» suites via Registry edit, to fix an immediate problem and guard against future problems. But if you cannot (or will not) edit the Registry, then numerous workarounds (not necessarily pretty) come to mind. For example: your .NET program could delegate its SSL traffic to a separate Python program (which may itself work, for the same reason that Chrome requests may succeed where MSIE requests fail on an affected machine).

answered Jun 1, 2019 at 6:16

APW's user avatar

APWAPW

3544 silver badges6 bronze badges

1

This one is working for me in MVC webclient

public string DownloadSite(string RefinedLink)
{
    try
    {
        Uri address = new Uri(RefinedLink);

        ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

        System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

        using (WebClient webClient = new WebClient())
        {
            var stream = webClient.OpenRead(address);
            using (StreamReader sr = new StreamReader(stream))
            {
                var page = sr.ReadToEnd();

                return page;
            }
        }

    }
    catch (Exception e)
    {
        log.Error("DownloadSite - error Lin = " + RefinedLink, e);
        return null;
    }
}

soccer7's user avatar

soccer7

3,4193 gold badges29 silver badges49 bronze badges

answered Oct 4, 2017 at 7:14

Arun Prasad E S's user avatar

Arun Prasad E SArun Prasad E S

9,3438 gold badges73 silver badges86 bronze badges

3

«The request was aborted: Could not create SSL/TLS secure channel» exception can occur if the server is returning an HTTP 401 Unauthorized response to the HTTP request.

You can determine if this is happening by turning on trace-level System.Net logging for your client application, as described in this answer.

Once that logging configuration is in place, run the application and reproduce the error, then look in the logging output for a line like this:

System.Net Information: 0 : [9840] Connection#62912200 - Received status line: Version=1.1, StatusCode=401, StatusDescription=Unauthorized.

In my situation, I was failing to set a particular cookie that the server was expecting, leading to the server responding to the request with the 401 error, which in turn led to the «Could not create SSL/TLS secure channel» exception.

HoldOffHunger's user avatar

answered Aug 19, 2014 at 19:55

Jon Schneider's user avatar

Jon SchneiderJon Schneider

25.5k23 gold badges140 silver badges168 bronze badges

1

Another possibility is improper certificate importation on the box. Make sure to select encircled check box. Initially I didn’t do it, so code was either timing out or throwing same exception as private key could not be located.

certificate importation dialog

answered Jul 11, 2012 at 22:27

Sherlock's user avatar

SherlockSherlock

1,0228 silver badges19 bronze badges

1

Doing this helped me:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

answered Jan 26, 2021 at 22:39

Merlyn007's user avatar

Merlyn007Merlyn007

4341 gold badge7 silver badges21 bronze badges

0

Finally found solution for me.

Try this adding below line before calling https url (for .Net framework 4.5):

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Luis Teijon's user avatar

Luis Teijon

4,7517 gold badges36 silver badges57 bronze badges

answered Jun 16, 2021 at 5:24

Priyank Sharma's user avatar

0

I had this problem because my web.config had:

<httpRuntime targetFramework="4.5.2" />

and not:

<httpRuntime targetFramework="4.6.1" />

answered Aug 15, 2017 at 10:47

Terje Solem's user avatar

Terje SolemTerje Solem

8061 gold badge10 silver badges25 bronze badges

1

In my case, the service account running the application did not have permission to access the private key. Once I gave this permission, the error went away

  1. mmc
  2. certificates
  3. Expand to personal
  4. select cert
  5. right click
  6. All tasks
  7. Manage private keys
  8. Add the service account user

answered Nov 13, 2017 at 21:24

Dinesh Rajan's user avatar

Dinesh RajanDinesh Rajan

2,35623 silver badges19 bronze badges

1

As you can tell there are plenty of reasons this might happen. Thought I would add the cause I encountered …

If you set the value of WebRequest.Timeout to 0, this is the exception that is thrown. Below is the code I had… (Except instead of a hard-coded 0 for the timeout value, I had a parameter which was inadvertently set to 0).

WebRequest webRequest = WebRequest.Create(@"https://myservice/path");
webRequest.ContentType = "text/html";
webRequest.Method = "POST";
string body = "...";
byte[] bytes = Encoding.ASCII.GetBytes(body);
webRequest.ContentLength = bytes.Length;
var os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
webRequest.Timeout = 0; //setting the timeout to 0 causes the request to fail
WebResponse webResponse = webRequest.GetResponse(); //Exception thrown here ...

answered Apr 25, 2014 at 20:50

TCC's user avatar

TCCTCC

2,5461 gold badge24 silver badges35 bronze badges

1

The root of this exception in my case was that at some point in code the following was being called:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

This is really bad. Not only is it instructing .NET to use an insecure protocol, but this impacts every new WebClient (and similar) request made afterward within your appdomain. (Note that incoming web requests are unaffected in your ASP.NET app, but new WebClient requests, such as to talk to an external web service, are).

In my case, it was not actually needed, so I could just delete the statement and all my other web requests started working fine again. Based on my reading elsewhere, I learned a few things:

  • This is a global setting in your appdomain, and if you have concurrent activity, you can’t reliably set it to one value, do your action, and then set it back. Another action may take place during that small window and be impacted.
  • The correct setting is to leave it default. This allows .NET to continue to use whatever is the most secure default value as time goes on and you upgrade frameworks. Setting it to TLS12 (which is the most secure as of this writing) will work now but in 5 years may start causing mysterious problems.
  • If you really need to set a value, you should consider doing it in a separate specialized application or appdomain and find a way to talk between it and your main pool. Because it’s a single global value, trying to manage it within a busy app pool will only lead to trouble. This answer: https://stackoverflow.com/a/26754917/7656 provides a possible solution by way of a custom proxy. (Note I have not personally implemented it.)

Community's user avatar

answered Sep 16, 2016 at 23:54

Tyler Forsythe's user avatar

1

If you are running your code from Visual Studio, try running Visual Studio as administrator. Fixed the issue for me.

answered Feb 27, 2018 at 16:59

handles's user avatar

handleshandles

7,63117 gold badges63 silver badges85 bronze badges

1

System.Net.WebException: The request was aborted: Could not create
SSL/TLS secure channel.

In our case, we where using a software vendor so we didn’t have access to modify the .NET code. Apparently .NET 4 won’t use TLS v 1.2 unless there is a change.

The fix for us was adding the SchUseStrongCrypto key to the registry. You can copy/paste the below code into a text file with the .reg extension and execute it. It served as our «patch» to the problem.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINESOFTWAREWow6432NodeMicrosoft.NETFrameworkv4.0.30319]
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINESOFTWAREMicrosoft.NETFrameworkv4.0.30319]
"SchUseStrongCrypto"=dword:00000001

answered Jul 26, 2018 at 14:35

capdragon's user avatar

capdragoncapdragon

14.5k24 gold badges106 silver badges153 bronze badges

3

I have struggled with this problem all day.

When I created a new project with .NET 4.5 I finally got it to work.

But if I downgraded to 4.0 I got the same problem again, and it was irreversable for that project (even when i tried to upgrade to 4.5 again).

Strange no other error message but «The request was aborted: Could not create SSL/TLS secure channel.» came up for this error

answered Dec 2, 2015 at 16:08

aghost's user avatar

aghostaghost

1922 silver badges8 bronze badges

2

In case that the client is a windows machine, a possible reason could be that the tls or ssl protocol required by the service is not activated.

This can be set in:

Control Panel -> Network and Internet -> Internet Options -> Advanced

Scroll settings down to «Security» and choose between

  • Use SSL 2.0
  • Use SSL 3.0
  • Use TLS 1.0
  • Use TLS 1.1
  • Use TLS 1.2

enter image description here

answered May 10, 2017 at 7:05

cnom's user avatar

cnomcnom

2,9914 gold badges29 silver badges60 bronze badges

4

none of this answer not working for me , the google chrome and postman work and handshake the server but ie and .net not working. in google chrome in security tab > connection show that encrypted and authenticated using ECDHE_RSA with P-256 and AES_256_GCM cipher suite to handshake with the server.

enter image description here

i install IIS Crypto and in cipher suites list on windows server 2012 R2 ican’t find ECDHE_RSA with P-256 and AES_256_GCM cipher suite. then i update windows to the last version but the problem not solve. finally after searches i understood that windows server 2012 R2 not support GSM correctly and update my server to windows server 2016 and my problem solved.

answered May 31, 2020 at 5:46

sina alizadeh's user avatar

I was having this same issue and found this answer worked properly for me. The key is 3072. This link provides the details on the ‘3072’ fix.

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

XmlReader r = XmlReader.Create(url);
SyndicationFeed albums = SyndicationFeed.Load(r);

In my case two feeds required the fix:

https://www.fbi.gov/feeds/fbi-in-the-news/atom.xml
https://www.wired.com/feed/category/gear/latest/rss

Stephen Rauch's user avatar

Stephen Rauch

47.5k31 gold badges106 silver badges135 bronze badges

answered May 27, 2018 at 14:02

joeydood's user avatar

joeydoodjoeydood

511 silver badge4 bronze badges

1

None of the answers worked for me.

This is what worked:

Instead of initializing my X509Certifiacte2 like this:

   var certificate = new X509Certificate2(bytes, pass);

I did it like this:

   var certificate = new X509Certificate2(bytes, pass, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

Notice the X509KeyStorageFlags.Exportable !!

I didn’t change the rest of the code (the WebRequest itself):

// I'm not even sure the first two lines are necessary:
ServicePointManager.Expect100Continue = true; 
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

request = (HttpWebRequest)WebRequest.Create(string.Format("https://{0}.sii.cl/cvc_cgi/dte/of_solicita_folios", server));
request.Method = "GET";
request.Referer = string.Format("https://hercules.sii.cl/cgi_AUT2000/autInicio.cgi?referencia=https://{0}.sii.cl/cvc_cgi/dte/of_solicita_folios", servidor);
request.UserAgent = "Mozilla/4.0";
request.ClientCertificates.Add(certificate);
request.CookieContainer = new CookieContainer();

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    // etc...
}

In fact I’m not even sure that the first two lines are necessary…

answered Apr 30, 2019 at 17:58

sports's user avatar

sportssports

7,81314 gold badges71 silver badges129 bronze badges

2

Another possibility is that the code being executed doesn’t have the required permissions.

In my case, I got this error when using Visual Studio debugger to test a call to a web service. Visual Studio wasn’t running as Administrator, which caused this exception.

answered Oct 30, 2019 at 10:11

OfirD's user avatar

OfirDOfirD

8,9235 gold badges45 silver badges88 bronze badges

This fixed for me, add Network Service to permissions.
Right click on the certificate > All Tasks > Manage Private Keys… > Add… > Add «Network Service».

Lionel Gaillard's user avatar

answered Apr 6, 2018 at 6:27

jayasurya_j's user avatar

jayasurya_jjayasurya_j

1,4991 gold badge14 silver badges22 bronze badges

1

Оглавление

  • Проблема
  • Windows 7 и Windows 2008 R2
  • Windows RT 8.1, Windows 8.1, Windows Server 2012 R2
  • Windows 2008 (не путать с R2)
  • Другая ОС
  • Проблема с корневыми сертификатами в ОС

Проблема

Ошибка ‘Запрос был прерван: Не удалось создать защищенный канал SSL/TLS’ или что то же самое ‘The request was aborted: Could not create SSL/TLS secure channel’ может возникнуть в обновляторе при операциях скачивания, например, исправлений (патчей) к конфигурациям с сайта 1С.

Если эта ошибка возникает изредка и не влияет на общий ход операции (так как обновлятор делает 3 попытки с паузой при неудачном скачивании), то делать с этим ничего не нужно. Тут причина скорее во временных сбоях при работе сети или самого сервиса 1С.

Но если обновлятор вообще не может ничего скачивать и постоянно при попытках выдаёт эту ошибку, то дело в том, что у вас в операционной системе не установлены необходимые обновления для того, чтобы мог корректно функционировать  протокол TLS.

Он требуется обновлятору при подключении, например, к сервисам 1С. А так как обновлятор написан на .Net Framework, то он опирается во многих своих возможностях на библиотеки операционной системы (в случае c TLS речь идёт о библиотеке schannel.dll).

Windows 7 и Windows 2008 R2

1. Для этих ОС, прежде всего, вам нужно установить Service Pack 1, если он у вас ещё не установлен.

2. Далее нужно установить KB3140245.

3. После этого KB3020369.

4. И, наконец, KB3172605.

5. После этого перезагрузите сервер, чтобы изменения вступили в силу.

1. Для этих ОС нужно установить KB2919355

2. После этого перезагрузите сервер, чтобы изменения вступили в силу.

Windows 2008 (не путать с R2)

1. Service Pack 2

2. KB955430, KB2999226, KB956250, KB4074621, KB4019276, KB4493730, KB4474419, KB4537830

Другая ОС

Если вы столкнулись с этой ошибкой на ОС, отличной от описанных выше, пожалуйста напишите мне на helpme1c.box@gmail.com и я постараюсь совместно с вами подготовить такую же подробную инструкцию по точечной установке только необходимых обновлений для вашей ОС.

Проблема с корневыми сертификатами в ОС

Ошибка с созданием защищенного канала может быть также связана с тем, что в ОС не обновлены корневые сертификаты.

Подробнее об этом здесь: ссылка.

Как помочь сайту: расскажите (кнопки поделиться ниже) о нём своим друзьям и коллегам. Сделайте это один раз и вы внесете существенный вклад в развитие сайта. На сайте нет рекламы, но чем больше людей им пользуются, тем больше сил у меня для его поддержки.

Ситуация: 

С недавних пор наши приложения на .net 4.5 в функционал которых, кроме прочего, входит загрузка страниц с сайтов. Перестали работать на серверах Windows Werver 2008 R2 и Windows Server 2012 R2

Ошибка

Не удалось создать защищенный канал ssl/tls
или она же на английском
The request was aborted: Could not create SSL/TLS secure channel

Причем эти же приложения работали нормально на машинах разработчиков на Windows 10.

Разбор ситуации. Что не помогло

Сразу скажу — много форумов читали, много советов перепробовали — нам
не помогли такие действия:

игры с настройкой протокола в приложении

ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AlwaysGoodCertificate);

ServicePointManager.Expect100Continue = true;

ServicePointManager.DefaultConnectionLimit = 9999;

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

игры с переходом на более свежий фреймворк: 

пробовали и .NET 4.6.1 и .NET 4.7.2

Но попробуйте, может у вас другой случай (я думаю, в случае другой конфигурации машины — могут помочь)

Вот советы, которые нам не помогли

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)
https://stackoverflow.com/questions/26389899/disable-ssl-fallback-and-use-only-tls-for-outbound-connections-in-net-poodle

How to specify SSL protocol to use for WebClient class
https://stackoverflow.com/questions/30491716/how-to-specify-ssl-protocol-to-use-for-webclient-class

.Net WebClient: Could not create SSL/TLS secure channel
https://www.aspsnippets.com/Articles/Net-WebClient-Could-not-create-SSLTLS-secure-channel.aspx

Запрос был прерван: Не удалось создать защищенный канал SSL/TLS
https://answer-id.com/ru/74496884

Запрос был прерван: не удалось создать безопасный канал SSL / TLS
https://qastack.ru/programming/2859790/the-request-was-aborted-could-not-create-ssl-tls-secure-channel

Не удалось создать защищенный канал SSL/TLS только на сервере Windows Server 2012
https://coderoad.ru/59975964/%D0%9D%D0%B5-%D1%83%D0%B4%D0%B0%D0%BB%D0%BE%D1%81%D1%8C-%D1%81%D0%BE%D0%B7%D0%B4%D0%B0%D1%82%D1%8C-%D0%B7%D0%B0%D1%89%D0%B8%D1%89%D0%B5%D0%BD%D0%BD%D1%8B%D0%B9-%D0%BA%D0%B0%D0%BD%D0%B0%D0%BB-SSL-TLS-%D1%82%D0%BE%D0%BB%D1%8C%D0%BA%D0%BE-%D0%BD%D0%B0-%D1%81%D0%B5%D1%80%D0%B2%D0%B5%D1%80%D0%B5-Windows-Server

How to enable TLS 1.2 on the site servers and remote site systems
https://docs.microsoft.com/en-us/mem/configmgr/core/plan-design/security/enable-tls-1-2-server

How to enable TLS 1.2 on clients
https://docs.microsoft.com/en-us/mem/configmgr/core/plan-design/security/enable-tls-1-2-client

Разбор ситуации 2: Варианты решения

Продолжили наши разбирательства, и, думаем, нашли причину ошибки и
2 возможных варианта решения:

Наиболее вероятная причина ошибки

Старые операционки не поддерживают новые наборы шифрования протокола TLS 1.2

Суть наших умозаключений 

похоже, что проблема в наборах шифрования (Cipher Suites)

попытался их внимательнее поразбирать с помощью статьи
https://docs.microsoft.com/en-us/answers/questions/227738/windows-server-2012-r2-tls-12-cipher-suites.html

не помогло.

Продолжили разбирательство

Вот Cipher Suites для разных операционных систем
https://docs.microsoft.com/en-us/windows/win32/secauthn/cipher-suites-in-schannel

по наводкам из статьи установил

IISCrypto
https://www.nartac.com/Products/IISCrypto

Увидел: на локальной машине есть такой набор 
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384

он же используется и на веб сайте с которого хотим загружать страницы

это я посмотрел через сайт
https://www.ssllabs.com/ssltest/analyze.html

Вот раздел с наборами шифрования

Cipher Suites

# TLS 1.3 (server has no preference)

TLS_AES_128_GCM_SHA256 (0x1301)   ECDH x25519 (eq. 3072 bits RSA)   FS 128
TLS_CHACHA20_POLY1305_SHA256 (0x1303)   ECDH x25519 (eq. 3072 bits RSA)   FS 256
TLS_AES_256_GCM_SHA384 (0x1302)   ECDH x25519 (eq. 3072 bits RSA)   FS 256

# TLS 1.3 (server has no preference)

TLS_AES_128_GCM_SHA256 (0x1301)   ECDH x25519 (eq. 3072 bits RSA)   FS 128
TLS_CHACHA20_POLY1305_SHA256 (0x1303)   ECDH x25519 (eq. 3072 bits RSA)   FS 256
TLS_AES_256_GCM_SHA384 (0x1302)   ECDH x25519 (eq. 3072 bits RSA)   FS 256

# TLS 1.2 (suites in server-preferred order)

TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (0xc030)   ECDH x25519 (eq. 3072 bits RSA)   FS 256
TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 (0xcca8)   ECDH x25519 (eq. 3072 bits RSA)   FS 256
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (0xc02f)   ECDH x25519 (eq. 3072 bits RSA)   FS 128

но, к сожалению, наборы не поддерживается в виндовс сервер 2012
https://docs.microsoft.com/en-us/windows/win32/secauthn/tls-cipher-suites-in-windows-8-1

и тем более в Windows Server 2008
https://docs.microsoft.com/en-us/windows/win32/secauthn/tls-cipher-suites-in-windows-7

а поддерживается только в Windows 10 (Windows Server 2016+)
https://docs.microsoft.com/en-us/windows/win32/secauthn/tls-cipher-suites-in-windows-10-v1607

Поизучали возможность обновления этих пакетов

How to Update Your Windows Server Cipher Suite for Better Security
https://www.howtogeek.com/221080/how-to-update-your-windows-server-cipher-suite-for-better-security/

Но, похоже, тут только возможность упорядочивания их, но новый пакет в ОС добавить вручную нельзя.

Вот более подробный разбор этой темы
Windows Server 2012 R2 TLS 1.2 Cipher Suites
https://docs.microsoft.com/en-us/answers/questions/227738/windows-server-2012-r2-tls-12-cipher-suites.html

вроде бы неудача…
но, в форумах часто проскальзывает что «хром работает, а .NET Framework приложения — нет». Причина в том, что баузер хром использует свои пакеты шифрования а не полагается ОС.
Мы зацепились за эту идею.

В одном из проектов мы использовали компонент — внедренный браузер на Chromium

пакет в Nuget: CefSharp.Winforms, CefSharp.Common.

Попробовали загрузить страницу через этот механизм — работает!

Решения

то есть у вас есть 2 варианта решения

1. переход на свежий Windows Server 2016

2. использование пакета CefSharp но предупреждаю, он увеличивает размер приложения (в нашем случае на 100+ МБ)

Выбор за вами :)

Если нужны будут детальные инструкции по CefSharp -напишите в комментах: сделаю отдельную статью.

Материалы по теме

Как узнать версию TLS на сайте
https://ru.wikihow.com/%D1%83%D0%B7%D0%BD%D0%B0%D1%82%D1%8C-%D0%B2%D0%B5%D1%80%D1%81%D0%B8%D1%8E-TLS-%D0%BD%D0%B0-%D1%81%D0%B0%D0%B9%D1%82%D0%B5

Страница для анализа SSL на нужном сайте(домене)
https://www.ssllabs.com/ssltest/analyze.html

How to Update Your Windows Server Cipher Suite for Better Security
https://www.howtogeek.com/221080/how-to-update-your-windows-server-cipher-suite-for-better-security/

Cipher Suites in TLS/SSL (Schannel SSP)
https://docs.microsoft.com/en-us/windows/win32/secauthn/cipher-suites-in-schannel

Demystifying Schannel
https://techcommunity.microsoft.com/t5/core-infrastructure-and-security/demystifying-schannel/ba-p/259233

Having this issue on Windows Server 2012 R2 with VS 2019 16.10. Workarounds had no effect. Updated to latest 16.11 and still nothing.

Running dotnet add runs successfully but the package manager and nuget CLI 5.11.0.10 exhibit this behavior and will not work.

EDIT: Correction, dotnet add does NOT work. Using .NET 5.0.401

error: Unable to load the service index for source https://api.nuget.org/v3/inde
x.json.
error:   The SSL connection could not be established, see inner exception.
error:   Unable to read data from the transport connection: An existing connecti
on was forcibly closed by the remote host..
error:   An existing connection was forcibly closed by the remote host.

Could not create SSL/TLS secure channel error occurs when a client is unable to establish a secure connection with a server using the SSL or TLS protocol.could not create ssl tls secure channel

This can arise from a variety of issues, such as an outdated security certificate on the server. In this post, you will learn about the causes and solutions to this error. Read on to find out.

Contents

  • What Causes the Could Not Create SSL/Tls Secure Channel Error?
    • – Outdated Security Certificate on the Server – Common Cause
    • – Mismatch in SSL/TLS Versions on the Client and Server
    • – Failure to Properly Configure the Server’s SSL/TLS Settings
    • – Using Self-signed Certificates Instead of Commercial Ones
    • – Using Free SSL Certificates – They Can Be Unpredictable
    • – Common Mistakes in The Program
  • Solutions to Could Not Create SSL/TLS Secure Channel Error
    • – Ensure Client and Server Use Compatible SSL/TLS Versions
    • – Disable SSL/TLS Compression To Eliminate the Error
    • – Enable SSL/TLS Caching To Speed Up SSL/TLS Negotiation
    • – Configure the Server To Use a Specific SSL/TLS Protocol
    • – Troubleshoot the Issue – Analyze the Error and Log Data
  • Conclusion

The could not create SSL/TLS secure channel error is caused when a client is unable to establish a secure connection with a server using the SSL or TLS protocol. This often arises from various issues, such as an outdated security certificate on the server.

Also, you will get this error if there is a mismatch in the SSL/TLS versions supported by the client and server. As well, if you fail to configure the server’s SSL/TLS settings properly, you will trigger this error.

In general, this error message is a sign that there is a problem with the SSL/TLS connection. The exact cause and solution will depend on the specific details of the client and server configurations. Below is a quick look at the several potential causes, each with its own unique set of circumstances.

– Outdated Security Certificate on the Server – Common Cause

One of the most common causes of the error is an outdated security certificate on the server. If a server’s certificate has expired, the client’s browser will be unable to establish a secure connection, resulting in this error message.

Security certificates, also known as digital certificates, are used to authenticate the identity of the server to the client and to establish a secure connection between them. A security certificate has an expiration date, and when that date passes, the certificate is no longer considered valid.

Thus, if a client tries to establish a connection with a server that has an expired certificate, the client’s browser will be unable to verify the server’s identity, and the connection will fail, resulting in this error.

Additionally, if the certificate is revoked, it is not considered valid anymore, and the connection will also fail with the error message. This happens when the issuing authority of the certificate revokes it due to a security issue with the certificate.

– Mismatch in SSL/TLS Versions on the Client and Server

Another common cause of the error is a mismatch in the SSL/TLS versions supported by the client and server. SSL and TLS are the security protocols that encrypt the data sent between the client and server, and different versions of these protocols have different capabilities.

If the client and server are using different versions, they may not be able to communicate securely.Could Not Create SSL TLS Secure Channel Causes

For example, if the client supports the latest version of TLS, say TLS 1.3, and the server only supports an older version, like TLS 1.2, the connection will fail. The client will try to establish a connection with the latest version of the protocol, but the server will not be able to understand it, resulting in this error message.

– Failure to Properly Configure the Server’s SSL/TLS Settings

Failure to properly configure the server’s SSL/TLS settings can also lead to the error. This could include issues such as using the wrong cipher suites or not properly configuring the server’s certificate chain.

One aspect of SSL/TLS configuration that is important to get right is the selection of cipher suites. These are sets of cryptographic algorithms that are used to secure the connection between the client and server. If the server is configured with the wrong cipher suites, or if the client and server do not have any cipher suites in common, the connection will fail, and the error in question will appear.

Another important factor is the server’s certificate chain. A certificate chain is a series of digital certificates that are used to authenticate the server’s identity. If the server’s certificate chain is not properly configured, the client’s browser will be unable to verify the server’s identity, and the connection will fail.

– Using Self-signed Certificates Instead of Commercial Ones

A self-signed certificate is a certificate that is signed by the owner of the certificate rather than a trusted certificate authority (CA). This can cause the error in question in a few ways.

Firstly, because a self-signed certificate is not issued by a trusted CA, it is not automatically considered a valid certificate by most web browsers and clients. This means that the client’s browser will be unable to verify the server’s identity, and the connection will fail, triggering the error message.

Secondly, self-signed certificates are not considered to be as secure as those issued by a trusted CA. They do not have the same level of encryption and security features associated with commercial certificates. This means that the connection may not be as secure as it would be with a certificate issued by a trusted CA and this can result in this error.

Lastly, self-signed certificates are not automatically added to the trusted list of browsers and devices. Therefore, the client’s browser will not trust the certificate and will fail to establish a secure connection causing this error.

– Using Free SSL Certificates – They Can Be Unpredictable

Free SSL certificates can cause this error in several ways. First, free SSL certificates may have limitations in terms of the level of encryption and security features they offer compared to paid certificates. This means that the connection may not be as secure as it would be with a paid certificate, which can trigger this error message.Could Not Create SSL TLS Secure Channel Reasons

Second, free SSL certificates may not be as widely recognized and trusted by web browsers and clients as certificates issued by well-known and reputable certificate authorities. This means that the client’s browser may not trust the certificate, and the connection will fail, generating this error.

In addition, some free SSL certificates may have limitations on the validity period, which can cause the certificate to expire before the expected time. This will lead to the error message as the browser will be unable to establish a secure connection with an expired certificate.

Other possible causes of the error include network issues or firewall restrictions. If there is a problem with the network connection between the client and server, or if the client’s firewall is blocking the connection, the error may occur.

– Common Mistakes in The Program

There are several instances when you may run into this error. Below is a quick look at some of the errors you may come across:

  • The request was aborted: could not create SSL/TLS secure channel iis: This error can occur when attempting to establish a secure connection using SSL/TLS on an IIS (Internet Information Services) server.
  • C# the request was aborted: could not create SSL/TLS secure channel: You can trigger this error when attempting to make an HTTPS request using C#.
  • The request was aborted: could not create SSL/ts secure channel windows 7: This error can occur when trying to make an HTTPS request on you Windows 7 computer.
  • The request was aborted: could not create SSL/TLS secure channel windows 10: The error can be triggered when attempting to make an HTTPS request on a computer running Windows 10.
  • C# could not create SSL/TLS secure channel: This error can occur when trying to make an HTTPS request using C#.
  • The request was aborted: could not create SSL/TLS secure channel git: The error can appear when attempting to make a connection with a remote Git repository over HTTPS.
  • The request was aborted: could not create ssl/tls secure channel httpclient c#: This error message occurs when you are attempting to make an HTTPS request using the HttpClient class in C#.
  • Could not create SSL/TLS secure channel windows server 2016: This error message appears when an SSL/TLS secure channel cannot be established between the client and server on Windows Server 2016.

Solutions to Could Not Create SSL/TLS Secure Channel Error

The first solution to the could not create SSL/TLS secure channel error entails verifying that the server’s security certificate is up-to-date and properly configured. This includes checking the expiration date of the certificate and renewing it before it expires. Also, you should ensure that the certificate is not revoked.

Doing this, you prevent the error from occurring due to an expired or revoked certificate. Also, you ensure that the client’s browser can verify the server’s identity and establish a secure connection. As well you get the added advantage of avoiding security vulnerabilities that may arise from using an expired or revoked certificate.

– Ensure Client and Server Use Compatible SSL/TLS Versions

It is important to ensure that both the client and server are using the same version of the protocol to establish a secure connection. This helps prevent the error from occurring due to a mismatch in SSL/TLS versions supported by the client and server. Also, you get to take advantage of the latest security features and encryption provided by the specific version of the protocol you choose.

– Disable SSL/TLS Compression To Eliminate the Error

Disabling SSL/TLS compression can help to prevent the error from occurring by eliminating the potential for compression-related attacks. The process involves turning off the compression feature that is built into the SSL/TLS protocol to reduce the amount of data that needs to be transmitted over the network.

By disabling SSL/TLS compression, you can prevent the error from occurring due to compression-related attacks. Also, you improve the security of the connection by eliminating a potential attack vector. In addition, you avoid any compatibility issues that may arise with certain clients or servers that do not support compression.

– Enable SSL/TLS Caching To Speed Up SSL/TLS Negotiation

Enabling SSL/TLS caching can help to resolve the error. This process involves storing the SSL/TLS session information on the client and server. It allows it to be reused in subsequent connections. This eliminates the need to renegotiate the session every time a connection is established. As such, caching can help to speed up the SSL/TLS negotiation process and reduce the risk of the error occurring.Could Not Create SSL TLS Secure Channel Fixes

When a client establishes an SSL/TLS connection with a server, the server sends back a session ID. The client then stores this session ID and the corresponding encryption keys.

If the client wishes to establish another SSL/TLS connection with the same server, it can reuse the session ID and encryption keys, which eliminates the need for a full SSL/TLS handshake. This speeds up the connection process and reduces the risk of this error occurring.

– Configure the Server To Use a Specific SSL/TLS Protocol

Configuring the server to use a specific SSL/TLS protocol is one of the solutions that can help to resolve the error. This process involves specifying which version of the SSL/TLS protocol the server should use when establishing a connection with a client. It can help ensure that the connection is established using a protocol that is known to be secure and compatible with the client.

– Troubleshoot the Issue – Analyze the Error and Log Data

Identify the root cause of the error by checking the client and server configurations and analyzing the error message and any other relevant log data. Troubleshooting the issue is an important step in resolving the error and preventing it from occurring in the future.

This process involves identifying the root cause of the error by reviewing the client and server configurations and analyzing the error message and relevant log data.

Once you establish the root cause of the error, you can then take the appropriate steps to resolve the issue. For example, if the cause of the error is an outdated security certificate, you can renew it.

If the cause is a mismatch in SSL/TLS versions, you can update the client and server to use the same version. In case the cause is a failure to properly configure the server’s SSL/TLS settings, you can review and update the settings accordingly.

Conclusion

In this post, you have learned about the causes of could not create ssl/tls secure channel error as well as its solutions. Below is a quick recap of this post that will help you quickly grasp the whole idea:

  • The error arises when it is not possible to establish a secure connection between the client and the server.
  • One cause of this error is an outdated security certificate on the server.
  • Also, you will trigger this error from a mismatch in SSL/TLS versions supported by the client and server as well as failure to properly configure the server’s SSL/TLS settings.
  • To solve this error, verify that the server’s security certificate is up-to-date and properly configured.
  • Also, ensure that the client and server are using compatible SSL/TLS versions.

With this understanding, you can now address this error thoroughly by checking the SSL/TLS configuration on both the client and server like a pro.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Возможно, вам также будет интересно:

  • Ошибка could not create socket
  • Ошибка could not create render target surface
  • Ошибка could not create d3d11 device в mad max
  • Ошибка could not convert variant of type
  • Ошибка could not connect to the database

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии