Wednesday, February 15, 2012

How to bypass server certificate error (underlying connection was closed)

Alternative Title 
  •  System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
  • Server Certificate validation error or Invalid server certificate
Problem 
There is a server that runs on HTTPS and after making HttpWebRequest to any URL client application throws error massage "The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."


Error Stack Trace 


The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.Source=System

StackTrace:
       at System.Net.HttpWebRequest.GetResponse()
       at ConsoleApplication1.Healpers.ExecuteGet(String url)
       at ConsoleApplication1.ODataService..ctor(String serviceURL)
       at ConsoleApplication1.Program.Main(String[] args)
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.Security.Authentication.AuthenticationException
       Message=The remote certificate is invalid according to the validation procedure.
       Source=System
       StackTrace:
            at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)


Root Cause 
Server is presenting a certificate to the client that is not trusted by either client machine of client application itself.

Solution 
Normally certificate verification bypassing is not suggested but there are several cases in which you know the server is trusted and do not want to take care of certificate validation error,
In such case you can use [ServicePointManager]


ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);

Just put one line of code at the start up of your application and it will mimic as certificate is valid. IE also handles the certificate errors in same way.

Multithreaded Application

This solution will not work in Multithreaded environment, we need to modify app.config 

<configuration>
   <system.net>
    <settings>
      <servicePointManager
          checkCertificateName="false"
          checkCertificateRevocationList="false"        
      />
    </settings>
  </system.net>
</configuration>
Refer to
  1. http://www.west-wind.com/weblog/posts/2011/Feb/11/HttpWebRequest-and-Ignoring-SSL-Certificate-Errors
  2. http://rob.gillenfamily.net/tag/tricks/#fbid=r0NCXNFk0Xr
Further References 




10 comments:

  1. I tried using this solution . It is not working for me. I am still getting the same error. I am using WebClient. The service which i am acessing has a self signed sertificate

    ReplyDelete
    Replies
    1. Hi Sriharsha thanks for you feedback , This solution is destined for HTTPWebRequest class and in-fact i do have faced strange problem with Web Client and finally I always used HTTPWebRequest/HTTPWebResponce.

      web Client is not as smart as HTTPWebRequest/HTTPWebResponce.
      However can you please share your detailed stack trace and authentication setting + SSL settings on server side

      I would suggest to post this question here http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/threads probably you will get the kind of solution you need

      Delete
    2. Hi Ashwini,
      Sorry it was my mistake. There was another method being called where webclient was again being used. I used your line of code before calling, now the issue is fixed. Going through some others code seems to be a tricky job ;):) . Any ways thank you for such a early reply and this useful article.

      Delete
    3. great to know that it worked for you

      Delete
  2. Hi,

    It works fine for .net 3.5/4.0/4.5 with win forms/wpf. But doesn't work with win store app. Any idea?
    -ursri

    ReplyDelete
  3. I have don`t have much knowledge of mobile application , but as for as I know all mobile application required DLL (client binaries ) to signed with a valid certificate , Are your binaries signed ?

    ReplyDelete
  4. Thanks for reply. The certificate associated is either localhost or that generated from makecert utility. Pls help further

    Thanks in advance
    ursri

    ReplyDelete
  5. Thanks a lot for this post! It helped me get over the certificate issue I was having very fast and continue development! Your blog is very helpful for developers.

    ReplyDelete
  6. I have tried all possible solutions and still doesnt work. Im getting the same error: "The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel." Could you please help me out? Im not sure what is exactly this: sender, certificate, chain, sslPolicyErrors ,.. do I have to pass specific values? Could you please provide me more details? Thank you in advanced

    ReplyDelete
  7. I have tried all possible solutions and still doesnt work. Im getting the same error: "The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel." Could you please help me out? Im not sure what is exactly this: sender, certificate, chain, sslPolicyErrors ,.. do I have to pass specific values? Could you please provide me more details? Thank you in advanced

    ReplyDelete