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

自古美人都是妖i 提交于 2021-02-11 13:36:08

问题


I have a windows service in a VM. It is calling an API hosted in another server. When I call that api from my windows service, it is giving me error saying :

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.

Now I know that if I add this line before calling the api, it will work fine.

System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };

But I do not want to change my code and deploy it again. Is there any way I can do something in the VM where windows service is hosted, like trusting the certificate or something , which will resolve this?

Any help in this regard is really helpful. Thanks.

I know this question is asked multiple time, but all the solutions require me to either change in the server where api is hosted or change my code to add above line. I'm looking for a solution where I can change in the client machine rather than anywhere else.


回答1:


I ran into this a few times. It could mean a few things:

  • Unsupported protocol(s) (SSL/TSL)
  • No matching cipher(s)
  • .NET Framework version < 4.6.1 needs special code

For the first two options, you could use nmap to determine the server's supported list of protocols and ciphers:

nmap -sV --script ssl-enum-ciphers -p 443 <host>

Once having the list of supported protocols/ciphers, you can then check your own on your client machine using a free tool called IISCrypto and verify that you have enabled matching protocol/cipher combinations.

For the last option, if you are running anything less than .NET Framework 4.6.1, you may need to add:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

I don't really suggest setting the protocols strictly as above (since TLS 1.3 is around the corner). Should always try to let windows determine the highest security for you. Sometimes certain evils are necessary to move forward. You can always revisit it later.

This has helped me solve this particular problem. Hopefully it will aid you with yours.



来源:https://stackoverflow.com/questions/59249053/system-net-webexception-the-underlying-connection-was-closed-could-not-establi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!