Could not establish secure channel for SSL/TLS C# Web service Client - c#

I have a WPF application and that calling 4 web services (Written with Java) on the same base URL and it was working perfectly until I install google chrome. I installed chrome and I've got this error:
Could not establish secure channel for SSL/TLS C# Web service
I didn't write another code. That happened for just I installed chrome then I remove chrome but didn't work and I tried system restore, uninstall eset smart security and I cleaned all windows(8.1 single languages) certificate. So how can I figure it out? Here is my web service caller
public string call(string url, string json)
{
try
{
var webrequest = (HttpWebRequest)WebRequest.Create(url);
var key = JsonConvert.SerializeObject(LoginService.SessionData.SessionKey);
UTF8Encoding uTF8Encoding = new UTF8Encoding();
byte[] requestBytes = uTF8Encoding.GetBytes(json);
WebClient client = new WebClient();
webrequest.Method = "POST";
webrequest.Headers.Add("SESSION_KEY", LoginService.SessionData.SessionKey);
webrequest.ContentType = "application/json";
webrequest.ContentLength = requestBytes.LongLength;
Stream requestStream = webrequest.GetRequestStream();//here the exception
requestStream.Write(requestBytes, 0, requestBytes.Length);
using (var response = webrequest.GetResponse())
using (var reader = new StreamReader(response.GetResponseStream()))
{
var responseBuf = reader.ReadToEnd();
String responseJson = Convert.ToString(responseBuf);
return responseJson;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
}

By my observation there are a large number of services over the last several months that are turning off SSL and/or older TLS versions to mitigate security problems inherent in them.
Anywhere within the AppDomain you can just force the connection to use TLS 1.2 like this:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
You can also OR together multiple versions if you need to support older ones as well:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12

Related

Unable to make HttpWebRequest that is working on Postman

I have a token request that works on Postman on a server.
No body, just basic authentication with username and password:
However, I have this code below that returns the error:
The request was aborted: Could not create SSL/TLS secure channel.
Here is the code below:
string responsedata = string.Empty;
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlToken);
request.Method = "POST";
request.Headers.Add("Authorization", "Basic " + encoded);
request.PreAuthenticate = true;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
responsedata = reader.ReadToEnd();
}
What am I doing worng?
I suspect your problem is related to the SecurityProtocol your application runs on.
Try running this before your request.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
The endpoint your trying to connect probably requires a higher version of Tls than what your application is providing.
The default value of this is defined by the system it runs on see:
https://learn.microsoft.com/en-us/dotnet/api/system.net.securityprotocoltype?view=net-7.0#system-net-securityprotocoltype-systemdefault
So when running on an older OS this often is too low for modern API endpoints.
You can test this by enabling or disabling specific versions of TLS/SSL in Postman, look for "Protocols disabled during handshake" in the settings tab for your request.
Like Neil Moss already commented above...
Think you are in use of untrusted certificate on server side so try to ignore certificate validation...
request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

The request was aborted: Could not create SSL/TLS secure channel. Asp.net c#

I have a problem uploading my application to the server with windows server 2012. It runs on my local computer, but when I run it on the server it responds with the following error:
The request was aborted: Could not create SSL/TLS secure channel.
This is my code:
ServicePointManager.Expect100Continue = true;
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string Token = "Token";
string url = "https://url";
string body = "{\"recipient_type\": \"individual\", \"to\": \"5214321776673\", \"type\": \"text\",\"text\": {\"body\": \"Hello, dear customer\"}}";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Api-Key", Token);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(body);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Response.Write(result);
}
}
I hope you can help me. Thank you.
On the server if the framework 3.5 , 4 , 4.5 and all its updates are installed.
I have also already reviewed the regedit and if it is found as they comment on it in different forums.
I have windows server 2012 and Internet Information Service 8 installed.

Http.WinHttpException sent on SOAP request .NET CORE 2.2. The message received was unexpected or badly formatted

We have three IHostedService in our .NETCore2.0 webapp performing operations periodically. Two of them are in polling on an external system asking for new data; the third sends to the same external system some data gathered by our webapp. Every request is SOAP and it's done with the following code:
try
{
#region PFC Certificate
// Pfx certificate management
string certPath = GetCertPath();
string certPass = GetCertPassword();
X509Certificate2Collection X509collection = new X509Certificate2Collection();
X509collection.Import(certPath, certPass, X509KeyStorageFlags.PersistKeySet);
#endregion
if (X509collection.Count > 0)
{
X509Certificate2 x509 = X509collection[0];
var request = CreateSOAPWebRequest(url, x509);
byte[] bytes;
bytes = Encoding.ASCII.GetBytes(xmlRequestContent);
request.ContentType = "application/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
if (request == null) throw new Exception($"url:{url}: Request NULL - xml: {xmlRequestContent}");
try
{
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
{
if (response.StatusCode == HttpStatusCode.OK)
{
using (Stream responseStream = response.GetResponseStream())
{
// Response deserialization
string responseStr = await new StreamReader(responseStream).ReadToEndAsync();
T result = new T();
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(responseStr))
{
result = (T)(serializer.Deserialize(reader));
return result;
}
}
}
}
}
catch (WebException ex)
{
_logger.LogError(ex);
throw;
}
}
return default(T);
}
catch(Exception ex)
{
_logger.LogError(ex);
throw;
}
The CreateSOAPWebRequest method is defined as:
private HttpWebRequest CreateSOAPWebRequest(string url, X509Certificate certificate)
{
Uri uri = new Uri(url);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Proxy = null;
webRequest.Headers.Add("SOAP:Action");
webRequest.KeepAlive = true;
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
webRequest.AuthenticationLevel = AuthenticationLevel.MutualAuthRequired;
if (certificate != null)
webRequest.ClientCertificates.Add(certificate);
return webRequest;
}
The first two hosted services worked very well together for years since the third cames in: some requests go OK in the beginning, then this exception is thrown and no one of the services is able to send the SOAP request anymore (until we restart the webapp):
The SSL connection could not be established, see inner exception. Authentication failed, see inner exception.
---> The SSL connection could not be established, see inner exception.
---> Authentication failed, see inner exception.
---> The message received was unexpected or badly formatted
This is thrown on the line
HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync()
This seems to be a certificate/security/SSL problem. But the requests work well in the beginning and/or without the third hosted service, so we thought it could be a syncronization problem between the services and we detached the third one by running it on a separate cloned webapp, alone, but we got the same error on the second SOAP call anyway (while the first worked).
We were able to reproduce this error in debug only by disabling the service in the production environment and running the webapp locally in debug mode, reading and sending production data.
We have no idea on what is causing this, so thank you in advance for every advice.
I finally figured it out. The whole thing was a bit misleading while the exception was telling the truth: at some point in our code, after the SOAP request, the flow COULD go through this:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
So everything was fine until this instruction and of course everything was broken after this instruction.

Zipwise.com Could not create SSL/TLS secure channel

I'm running into an issue with my application. When trying to use ZipWise.com's api to get some zip codes I get the error "The request was aborted: Could not create SSL/TLS secure channel." I did not make any changes to the program, and it all of a sudden stopped allowing me to use their API. I tried adding this to the beginning of my code before the request is created:
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
I disabled TLS 1.0, TLS 1.1, SSL 2.0, and SSL 3.0 on the server (and rebooted). I'm able to open the url in a browser without issue. I verified on SSL Labs that they are using TLS 1.2.
When I run this on my development PC, it executes without issue and returns a bunch of zip codes. When I try to run it on the server, it fails and gives me that error.
Here is some sample code I used in a Windows forms application that produces the same error:
private void button1_Click(object sender, EventArgs e)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.Expect100Continue = true;
string url = "https://zipwise.com/webservices/radius.php?key=**********&zip=90210&radius=50";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
request.Method = "POST";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();//exception occurs here
StreamReader input = null;
XDocument doc = null;
if (response.StatusCode.Equals(HttpStatusCode.OK))
{
input = new StreamReader(response.GetResponseStream());
doc = XDocument.Parse(input.ReadToEnd());
}
response.Close();
request.ServicePoint.CloseConnectionGroup(request.ConnectionGroupName);
if (input != null)
{
input.Close();
var tempZips = (from z in doc.Descendants("result") select z.Descendants("zip").Single().Value).ToList();
finalZips.AddRange(tempZips);
foreach(string s in finalZips)
{
listBox1.Items.Add(s);
}
}
}
Any help is appreciated!
EDIT: The application is running on .NET 4.6, The SSL Cert on the server is still valid.

Http post error: An existing connection was forcibly closed by the remote host

I realise there have been a number of similar posts to this but I haven't found a solution yet. Am trying to post some xml to an MPI gateway but keep getting the following error:
Unable to read data from the transport connection: An existing
connection was forcibly closed by the remote host.
Below is the code I'm currently using but have tried just about every different approach I can think of and they all return the same error:
string result = "";
string xml = "<TNSAuthRequest><CardNumber>0123456789</CardNumber><ExpiryDate>1801</ExpiryDate><PurchaseAmt>750</PurchaseAmt><CurrencyCode>826</CurrencyCode><CurrencyExponent>2</CurrencyExponent><CountryCode>826</CountryCode><MerchantName>Mayflower</MerchantName><MerchantId>0123456789</MerchantId><MerchantData>abcdefghijklmnopqrstuvwxyz0123456789</MerchantData><MerchantUrl>example.com</MerchantUrl><NotificationURL>example.com/basket</NotificationURL></TNSAuthRequest>";
var url = "https://mpi.securecxl.com";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes("xmldata=" + xml.ToString());
ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateRemoteCertificate);
var req = (HttpWebRequest)WebRequest.Create(url);
req.AllowWriteStreamBuffering = true;
req.ContentType = "text/xml";
req.Method = "POST";
//req.ContentLength = bytes.Length;
req.KeepAlive = false;
req.ProtocolVersion = HttpVersion.Version10;
req.ServicePoint.ConnectionLimit = 1;
//req.Timeout = -1;
try
{
using (var writer = new StreamWriter(req.GetRequestStream(), Encoding.ASCII))
{
writer.WriteLine(bytes);
}
using (WebResponse resp = req.GetResponse())
{
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
result = sr.ReadToEnd().Trim();
}
}
}
catch (Exception ex)
{
result = ex.Message + "<br />" + ex.InnerException.Message + "<br /><br />" + xml.Replace("<", "<");
}
ViewBag.result = result;
Am basically wandering if anyone can see anything that might be wrong with the code that could be causing this error or if it's most likely I problem on the their end? Have tried running on my localhost, our live server and my own private server (with a completely different IP) and still get same result.
Any ideas?
I think its because you are connecting to "https" url. In this case you have to add following line to your code.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
It will accept "ssl" protocol for your request. "ServicePointManager.ServerCertificateValidationCallback" handler just controls certificate validity.
Slightly better perhaps:
System.Net.ServicePointManager.SecurityProtocol = System.Net.ServicePointManager.SecurityProtocol | System.Net.SecurityProtocolType.Tls12;
#AlisettarHuseynli is right, this sometimes has to do with https. Most likely occurs when the infrastructure gets updates which may mean TLS gets updated for example from TLS1.0 to TLS1.2 Usually happens with some APIs, etcetera.
If the service you are trying to access can be accessed over http, do that. Change the scheme from https to http. Worked in my case. Otherwise you'll have to add code to support higher versions of TLS. Popular software usually have an opt-in option to use TLS1.2 instead of the old TLS1.0.

Categories