ServicePointManager.ServerCertificateValidationCallback not working on Windows Server 2012 R2 - c#

Before our application is deployed to our production environment, we call a number APIs in lower environments from our .NET web application. Those servers that host the APIs tend not to have certs signed by a trusted Certificate Authority.
I created the following code as a workaround, with a safety to exclude running this code in our production environment:
if (ignoreCertErrors && environmentName.ToLower() != "PROD")
{
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
}
Both ignoreCertErrors and environmentName are parameters provided to the method that contains this logic.
This worked on my local development box (Windows 7) but when I deployed it to Windows 2012 R2 test server, my calls to APIs with certs that aren't trusted still fail with the following errors:
=================================================================
Message: The underlying connection was closed: An unexpected error
occurred on a send. Stack Trace:
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResultar)
=================================================================
Message: Unable to read data from the transport connection: An
existing connection was forcibly closed by the remote host. Stack
Trace:
at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
=================================================================
Message: An existing connection was forcibly closed by the remote host
Stack Trace:
at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)
at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
=================================================================
Do I need change this logic, or do something new to ignore certificate warnings on Windows Server 2012 R2?

I'm going to approach this a different way, I've created a question related to the error messages and ask for suggestions to resolve.

Related

"Remote server returned an error: (407) Proxy Authentication Required" error when the application hit Rest API in C#

I am trying to connect the production Rest API, the api url starts with "https://"
I have been told that i have to use the certificate to connect the API. When i try to connect the api without certificate i am getting error as
Error: The underlying connection was closed: could not establish trust relationship for the SSL/TLS secure channel
I have received the Key store file which is already using in java to connect the same production rest api.
With the help of KeyStore file how do i use in C#. Any help appreciate.
Update:
Now we were able to connect the Rest api with the help of below line in from local development environment.
System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
Now we deployed the code in Stage, Now we are receiving the below error
error "Logging Error : System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException:
The remote server returned an error: (407) Proxy Authentication Required.\r\n at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)\r\n at
System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)\r\n --- End of inner exception stack trace ---One or more errors occurred."
Help me Please.

WebClient DownloadData SocketException

This is a very popular topic here, and I have read at least twenty different stackoverflow, expertsexchange, codeproject "solutions", and they boil down to things like: proxy servers (which they assure me isn't being used), and other things that just don't help me.
I have an image that is sitting out on this server. It can be publicly reached through a URL (I won't give that here, being this is a customer server). The URL that is exposed is through a Virtual Directory that is set up through IIS.
I opened Visual Studio and created a new ASP.NET Web Application - and I made it an empty project, and added one WebForm to it. Simple as simple can be.
The only code I added was to the WebForm Page_Load function:
protected void Page_Load(object sender, EventArgs e)
{
using (System.Net.WebClient wc = new System.Net.WebClient())
{
Uri myUri = new Uri(#"http://SERVER/folder/Image.bmp", UriKind.Absolute);
byte[] bytes = wc.DownloadData(myUri);
}
}
That's it. That's all I do.
Because that URL is publicly exposed, when I run it in Visual Studio. It works.
Also, at work, I have a Web Server with IIS (The IIS that comes with Windows Server 2008 R2 Standard - Service Pack 1). I just copied my whole project folder (after I built for release), plopped it on inetpub/wwwroot/, went to IIS, added it as an Application (using annonymous access, and the Default App Pool).
Here, at work, no problem! No errors.
Now, I do the same thing to their server. Just take the whole folder. Create an application, etc. etc. .... and as soon as I get to the DownloadData piece of code I get an exception:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond [redacted]:80
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond [redacted]:80
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SocketException (0x274c): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond [redacted]:80]
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +8409635
System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) +611
[WebException: Unable to connect to the remote server]
System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) +365
System.Net.WebClient.DownloadData(Uri address) +111
WebClientTest.WebForm1.Page_Load(Object sender, EventArgs e) in c:\Users\[me!!!]\Documents\Visual Studio 2013\Projects\WebClientTest\WebClientTest\WebForm1.aspx.cs:18
System.Web.UI.Control.OnLoad(EventArgs e) +103
System.Web.UI.Control.LoadRecursive() +68
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3811
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.2053.0
So, to recap:
Simple project works in my debugging environment. Check!
Works on my server at work. Check!
Doesn't work on client server. Not Check!
There has to be some explanation for this. Obviously I can see the host. So why, when they host this code, instead of me, does it fail to establish a connection? Finding this information, or what can cause this, is surprisingly difficult. It has to be some type of server setting, right?
Their server is Windows Server 2012 R2 Standard.
EDIT: I also want to mention that I can open a browser anywhere (my desktop, my VM which hosts my debugging environment, their server, etc.) and if I take that URL, the bitmap displays. No problem. As soon as IIS/ASP.NET get involved ... connections fail. This is so discouraging.
EDIT2: I have a public facing cloud server, that has the same setup (same type of virtual directory, an image, etc). So I added a second WebForm to this project. Same code in PageLoad, this time pointing to my server for the image, instead of theirs. That page works! There's definitely something on their server that is causing this. But what?

.NET System.Security.Authentication.AuthenticationException

We are connecting to a specific website using a TLS connection. We are enforcing TLS 1.2 as the only allowed protocol in the client code. In about 99% of all cases connection setup is OK and shows no errors. However from time to time we receive the following exception:
System.Security.Authentication.AuthenticationException: A call to SSPI failed, see inner exception. ---> System.ComponentModel.Win32Exception: The buffers supplied to a function was too small
--- End of inner exception stack trace ---
at System.Net.Security.SslState.EndProcessAuthentication(IAsyncResult result)
at Fw.Connections.Ssl.Private.ClientInstance.AuthenticateClientCallback(IAsyncResult result);
We have tested the remote server with SSL labs and we receive an A+ with no failures or problems reported, it's not a server under our control so the remote environment is not very well known.. We have tested the client code on Windows server 2012 (datacenter) and Windows7 clients. Both show the error from time to time. Is this a known bug in the .NET framework?

wcf client reporting SSL exception only on one occasion

Our WCF client normally invokes a web service. All deployments of the client invoke the same web service. In most deployments it makes the call without any issues, except in one instance it reports the following exception:
System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
at System.Net.PooledStream.EndWrite(IAsyncResult asyncResult)
at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
What could be different with this one installation?
We tested the URL that the client uses to make the call to the web service in the browser. The web service returns a response ok in Firefox but not in IE.
Have you seen this article yet? It contains fairly good tips for troubleshooting these issues: http://blogs.msdn.com/b/jpsanders/archive/2009/09/16/troubleshooting-asp-net-the-remote-certificate-is-invalid-according-to-the-validation-procedure.aspx?Redirected=true
For example, you'll need to check that the particular machine has all the root and intermediate certificates properly deployed.
I found the solution - there was a new web service server certificate installed with SHA256 and Windows 2003 Server requires a hotfix to support it:
http://support.microsoft.com/kb/938397

The underlying connection was closed: An unexpected error occured on a send

I am trying to run/debug locally my cloud project, but service bus connection keeps crashing with error:
<15:46:59> MessagingFactory successfully created
<15:47:39> Exception: The underlying connection was closed: An unexpected error occurred on a send..
....
System.IO.IOException: Unable to read data from the transport connection:
An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)
at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
--- End of inner exception stack trace ---
at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
at System.Net.PooledStream.EndWrite(IAsyncResult asyncResult)
at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)}
Also I receive this error when using Service Bus Explorer tool.
When deploy to cloud everything works ok, service bus connection is ok.
Can anyone help me with this? what could be the reason?
Thank you in advance!
Maybe the problem is with the SSL certificate validation protocol. Try this to force the latest protocol type.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
There are several reason leading to such error so you may check the following
You have configured the settings correctly.
Firewall in your system allows the connection (protocol, host & port)
DNS servers configured in your network are able to resolve the host.
Your ISP is not blocking your connection due to any reason
Since there is no fixed solution for your error, you may have to work a little hard to figure out the actual issue. You may also find some useful information from the log files if enabled.

Categories