.Net could not create SSL/TLS secure channel - c#

I am posting xml from a .net application to a third party web service but receive a "could not create SSL/TLS secure channel" error. When I make the request with soapUI it works fine and i get a response. But cant seem to get it from my .net console app.
I have tried setting the security to tls1 and tls12 but still no success. The certificate is installed on the server from which i am making these requests.
Is there anyone who has managed to solve this issue?
Here is a sample of my code
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://thirdPartyURL/cgi-bin/XmlProc");
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes("myXML");
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();

Fixed this by doing the following:
Changing the .Net Framework to 4.5
Installing the certificate in the "Third-Party Root Authorities" store
Added this line of code before making the request in my app
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
Ran the application on a windows server 2012 instead of windows server 2008. It might be a case that windows server 2008 does not support TLS v1.2

Related

C# HttpWebRequest returns 503 error for localhost url

I am calling localhost URL using C# HttWebRequest. It is returning a 503 service unavailable error in response.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri("http://127.0.0.1:42000/some/path"));
req.Method = "POST";
byte[] postArray = Encoding.UTF8.GetBytes("");
req.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
req.ContentLength = postArray.Length;
req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
response = (HttpWebResponse)req.GetResponse();
On a different computer it is working fine and also on web browser localhost URL is opening. Localhost is connected to AWS EC2 instance using tunnel on some port. What is cause of this issue?
I found out reason for it. Issue was due to HttpWebRequest was picking up system proxy automatically. So I set Proxy null in HttpWebRequest object in code req.Proxy = null; before making request. Issue was fixed after this.

Getting SSL/TLS error while scraping a secure website via C# and HttpWebRequest

I'm trying to write C# code to scrape html code from a secure website (i.e. https://www.exampe.com).
I'm using Visual Studio 2017 with .Net Framework 4.5.2.
This is my code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string html = reader.ReadToEnd();
}
When the above code is run, the following error is raised at line #2, GetResponse():
The request was aborted: Could not create SSL/TLS secure channel
When I use regular HTTP URL, then the above code works fine. It only breaks on HTTPS.
PS:
This website is external, meaning outside of our network and works fine when I view it via any browser. I assume it's got all necessary legitimate and valid certificates.
And by the way, my code works fine when I run it at home on a separate computer that's not connected to my company's network.
Please help!
This could be a TLS 1.2 problem. You have to tell C# to use TLS 1.2:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
add this code before your requests.
I found an answer to my question. All that needs to be done is to add the following line of code before creating a request:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
... and the rest is same as I had originally.
Now my app works great!
Thank you!

Windows Server 2016 - The request was aborted: Could not create SSL/TLS secure channel

I'm trying to send HttpWebRequest to a secure website using a client certificate through ASP.NET web app. The app is hosted on IIS under Windows Server 2016.
Whenever I try to send a request I'm receiving the following exception:
System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
The tricky part is that it works on my Windows 7 machine. I've managed to simulate at 100% the production environment and I've received the expected response.
Here is the code I'm using to send the request:
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.ClientCertificates.Add(this.Certificate);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
var stream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(stream))
{
string responseData = reader.ReadToEnd();
return responseData;
}

Could not create SSL/TLS secure channel. SecureChannelFailure

I'm getting an SSL error when making a SOAP call with an SSL certificate:
The request was aborted: Could not create SSL/TLS secure channel.
The weird thing is that if I load the certificate in Firefox and visit the endpoint or make a call to the API without sending any data, I don't get any error message and it connects successfully. The company exposing the API has also mentioned that the certificate is kosher.
The certificate I'm loading has full privileges to "Everyone". I've tried every solution I've seen on the internet but still getting the error.
Here is my code that creates the request:
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var request = (HttpWebRequest)WebRequest.Create(plugin.EndPoint);
request.ContentType = "text/xml; charset=utf-8";
request.Method = "POST";
The code to get the certificate (I've also tried with a pfx):
var cert = new
509Certificate2(#"C:\clientcert.p12", "FakePassword");
request.ClientCertificates.Add(cert);
and the code for the request:
byte[] byteArray = Encoding.UTF8.GetBytes(xml);
request.ContentLength = byteArray.Length;
using (var dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
using (WebResponse response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
StreamReader reader =
new StreamReader(responseStream ?? throw new InvalidOperationException());
return reader.ReadToEnd();
}
}
}
Edit:
Here is the trace output from running the request:
System.Net Information: 0 : [11844]
InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0,
returned code=CertUnknown). System.Net Error: 0 : [11844] Exception in
HttpWebRequest#63832831:: - The request was aborted: Could not create
SSL/TLS secure channel.. System.Net Error: 0 : [11844] Exception in
HttpWebRequest#63832831::EndGetRequestStream - The request was
aborted: Could not create SSL/TLS secure channel..
I also changed the SecurityProtocol:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
Second Edit: I can get it to work in SoapUI but not in the .NET application by just loading the SSL certificate from the file system in SOAP UI.
Out of interest, your app is using the TLS 1.0, 1.1 and 1.2 protocols, but is its use enabled in Internet Explorer?
If it's not in the web.config, add it
<appSettings>
<add key="SecurityProtocol" value="Tls12" />
</appSettings>
Then also check it's enabled in IE in the advanced settings tab: "Use TLS 1.2"
Your SSL certificate is signed by a root certificate that isn't installed in Windows.
Firefox ships with it's own trusted root cert list that contains the root cert for the cert you're using. Just because Firefox trusts a cert doesn't mean that Windows trusts it.
The solution is to install your cert's root cert or cert chain on the computer running your app.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-create-temporary-certificates-for-use-during-development
If this is an app with a wide audience, an easier solution is to switch to an SSL provider that already uses a root cert that ships with Windows.
Sometimes I have this error as well. The steps I take to overcome this problem are as follows:
Export your certificate from IIS
Double click the certificate and follow the wizard
Store location 'Local machine' next ->
Fill in the password you have picked during the export
Check the option to place the certificate in a store and choose your 'Trusted Root Certification Authorities'
Finish -> to check if the import was successful type in 'Windows search' 'certmgr.msc' navigate to the 'Trusted Root Certification Authorities' and then the certificates folder. The imported certificate should be present.
Test with your application.
I hope it helps

C# System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send

I'm getting this error on just one server running Windows Server 2003:
System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send.
Here's my code... Any ideas?
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https:// URL HERE ");
//request.Headers.Add("Accept", "application/xml");
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(xml);
request.KeepAlive = false;
request.Accept = "application/xml";
request.ContentType = "application/xml; charset='UTF-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
request.Timeout = 10000;
request.ServicePoint.Expect100Continue = false;
Setting the HttpWebRequest.KeepAlive to false didn't work for me.
Since I was accessing a HTTPS page I had to set the Service Point Security Protocol to Tls12.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Notice that there are other SecurityProtocolTypes:
SecurityProtocolType.Ssl3
SecurityProtocolType.Tls
SecurityProtocolType.Tls11
So if the Tls12 doesn't work for you, try the three remaining options.
Also notice you can set multiple protocols. This is preferable on most cases.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12| SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
Edit: Since this is a choice of security standards it's obviously best to go with the latest (TLS 1.2 as of writing this), and not just doing what works. In fact, SSL3 has been officially prohibited from use since 2015 and TLS 1.0 and TLS 1.1 will likely be prohibited soon as well. source: #aske-b
I was getting the same error, using RestSharp with .NET 4.5. I tested the same URL with cURL and it worked fine. After a long time debugging I found that setting the SecurityProtocol fixed the issue.
See: "The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate
In my case, I forgot to remove the "s" from "https" when I was swapping URLs between environments. I was hitting Localhost with https on accident. Same thing would occur if you are hitting an http site with no https certificate, or an expired certificate.
This problem may occur in this case, you will want to download a link that is a filter link and you do not have permission to download that link.
I have faced with this error while I was deploying a nuget package to nexus server manually from command line with API-KEY.
I have checked the nexus server configuration and I have realized Nexus NuGet API-Key Realm is not activated. I have activated it and tried again, everythings worked fine.
So, You should check server side to confirm you have activated related realms.
I was getting this error trying to download an rss file with HttpWebRequest. When I tested in a browser, and checked the response codes, the url was fine.
After trying everything here, it occurred to me the site might be blocking based on User Agent.
Changing the User Agent string in the request worked :
let request = WebRequest.Create(url) :?> HttpWebRequest
request.UserAgent <- #"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"
let response = request.GetResponse()
This User Agent String came from typing "what's my user agent" in Google Chrome
This problem occurs when the client computer cannot send an HTTP request. The client computer cannot send the HTTP request because the connection has been closed or is unavailable. This problem may occur when the client computer is sending lots of data. To resolve this problem, see resolutions A, D, E, F, and O.
https://support.microsoft.com/en-us/kb/915599

Categories