Could not establish trust relationship for SSL/TLS secure channel -- SOAP

C#.NetSslTrust

C# Problem Overview


I have a simple web service call, generated by a .NET (C#) 2.0 Windows app, via the web service proxy generated by Visual Studio, for a web service also written in C# (2.0). This has worked for several years, and continues to do so at the dozen or so places where it is running.

A new installation at a new site is running into a problem. When attempting to invoke the web service, it fails with the message saying:

> Could not establish a trust relationship for the SSL/TLS secure > channel

The URL of the web service uses SSL (https://) -- but this has been working for a long time (and continues to do so) from many other locations.

Where do I look? Could this be a security issue between Windows and .NET that is unique to this install? If so, where do I set up trust relationships? I'm lost!

C# Solutions


Solution 1 - C#

The following snippets will fix the case where there is something wrong with the SSL certificate on the server you are calling. For example, it may be self-signed or the host name between the certificate and the server may not match.

This is dangerous if you are calling a server outside of your direct control, since you can no longer be as sure that you are talking to the server you think you're connected to. However, if you are dealing with internal servers and getting a "correct" certificate is not practical, use the following to tell the web service to ignore the certificate problems and bravely soldier on.

The first two use lambda expressions, the third uses regular code. The first accepts any certificate. The last two at least check that the host name in the certificate is the one you expect.
... hope you find it helpful

//Trust all certificates
System.Net.ServicePointManager.ServerCertificateValidationCallback =
    ((sender, certificate, chain, sslPolicyErrors) => true);

// trust sender
System.Net.ServicePointManager.ServerCertificateValidationCallback
                = ((sender, cert, chain, errors) => cert.Subject.Contains("YourServerName"));

// validate cert by calling a function
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);

// callback used to validate the certificate in an SSL conversation
private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors)
{
    bool result = cert.Subject.Contains("YourServerName");
    return result;
}

Solution 2 - C#

The very simple "catch all" solution is this:

System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

The solution from sebastian-castaldi is a bit more detailed.

Solution 3 - C#

Thoughts (based on pain in the past):

  • do you have DNS and line-of-sight to the server?
  • are you using the correct name from the certificate?
  • is the certificate still valid?
  • is a badly configured load balancer messing things up?
  • does the new server machine have the clock set correctly (i.e. so that the UTC time is correct [ignore local time, it is largely irrelevent]) - this certainly matters for WCF, so may impact regular SOAP?
  • is there a certificate trust chain issue? if you browse from the server to the soap service, can you get SSL?
  • related to the above - has the certificate been installed to the correct location? (you may need a copy in Trusted Root Certification Authorities)
  • is the server's machine-level proxy set correctly? (which different to the user's proxy); see proxycfg for XP / 2003 (not sure about Vista etc)

Solution 4 - C#

I personally like the following solution the most:

using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

... then before you do request getting the error, do the following

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

Found this after consulting Luke's Solution

Solution 5 - C#

If you do not wan't to blindly trust everybody and make a trust exception only for certain hosts the following solution is more appropriate.

public static class Ssl
{
	private static readonly string[] TrustedHosts = new[] {
	  "host1.domain.com", 
	  "host2.domain.com"
	};

	public static void EnableTrustedHosts()
	{
	  ServicePointManager.ServerCertificateValidationCallback = 
	  (sender, certificate, chain, errors) =>
	  {
		if (errors == SslPolicyErrors.None)
		{
		  return true;
		}

		var request = sender as HttpWebRequest;
		if (request != null)
		{
		  return TrustedHosts.Contains(request.RequestUri.Host);
		}

		return false;
	  };
	}
}

Then just call Ssl.EnableTrustedHosts when your app starts.

Solution 6 - C#

If you are using Windows 2003, you can try this:

> Open Microsoft Management Console > (Start --> Run --> mmc.exe); > > Choose File --> Add/Remove Snap-in; > > In the Standalone tab, choose Add; > > Choose the Certificates snap-in, and > click Add; > > In the wizard, choose the Computer > Account, and then choose Local > Computer. Press Finish to end the > wizard; > > Close the Add/Remove Snap-in dialog; > > Navigate to Certificates (Local > Computer) and choose a store to > import: > > If you have the Root CA certificate > for the company that issued the > certificate, choose Trusted Root > Certification Authorities; > > If you have the certificate for the > server itself, choose Other People > > Right-click the store and choose All > Tasks --> Import > > Follow the wizard and provide the > certificate file you have; > > After that, simply restart IIS and try > calling the web service again.

Reference: http://www.outsystems.com/NetworkForums/ViewTopic.aspx?Topic=Web-Services:-Could-not-establish-trust-relationship-for-the-SSL/TLS-...

Solution 7 - C#

Microsoft's SSL Diagnostics Tool may be able to help identify the issue.

UPDATE the link has been fixed now.

Solution 8 - C#

Luke wrote a pretty good article about this .. pretty straight forward .. give this a try

Luke's Solution

Reason (quote from his article (minus cursing)) ".. The problem with the code above is that it doesn’t work if your certificate is not valid. Why would I be posting to a web page with and invalid SSL certificate? Because I’m cheap and I didn’t feel like paying Verisign or one of the other ****-***s for a cert to my test box so I self signed it. When I sent the request I got a lovely exception thrown at me:

System.Net.WebException The underlying connection was closed. Could not establish trust relationship with remote server.

I don’t know about you, but to me that exception looked like something that would be caused by a silly mistake in my code that was causing the POST to fail. So I kept searching, and tweaking and doing all kinds of weird things. Only after I googled the ***n thing I found out that the default behavior after encountering an invalid SSL cert is to throw this very exception. .."

Solution 9 - C#

I just encountered this issue. My resolution was to update the system time by manually syncing to the time servers. To do this you can:

  • Right-click the clock in the task bar
  • Select Adjust Date/Time
  • Select the Internet Time tab
  • Click Change Settings
  • Select Update Now

In my case this was syncing incorrectly so I had to click it several times before it updated correctly. If it continues to update incorrectly you can even try using a different time server from the server drop-down.

Solution 10 - C#

I had a similar problem in .NET app in Internet Explorer.

I solved the problem adding the certificate (VeriSign Class 3 certificate in my case) to trusted editors certificates.

Go to Internet Options-> Content -> Publishers and import it

You can get the certificate if you export it from:

Internet Options-> Content -> Certificates -> Intermediate Certification Authorities -> VeriSign Class 3 Public Primary Certification Authority - G5

thanks

Solution 11 - C#

Try this:

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

Notice that you have to work at least with 4.5 .NET framework

Solution 12 - C#

add this:

 ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;}

right before the line that you're calling the service

Solution 13 - C#

I had this error running against a webserver with url like:

a.b.domain.com

but there was no certificate for it, so I got a DNS called

a_b.domain.com

Just putting hint to this solution here since this came up top in google.

Solution 14 - C#

For those who are having this issue through a VS client side once successfully added a service reference and trying to execute the first call got this exception: “The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel” If you are using (like my case) an endpoint URL with the IP address and got this exception, then you should probably need to re-add the service reference doing this steps:

  • Open the endpoint URL on Internet Explorer.
  • Click on the certificate error (red icon in address bar)
  • Click on View certificates.
  • Grab the issued to: "name" and replace the IP address or whatever name we were using and getting the error for this "name".

Try again :). Thanks

Solution 15 - C#

In my case I was trying to test SSL in my Visual Studio environment using IIS 7.

This is what I ended up doing to get it to work:

  • Under my site in the 'Bindings...' section on the right in IIS, I had to add the 'https' binding to port 443 and select "IIS Express Developement Certificate".

  • Under my site in the 'Advanced Settings...' section on the right I had to change the 'Enabled Protocols' from "http" to "https".

  • Under the 'SSL Settings' icon I selected 'Accept' for client certificates.

  • Then I had to recycle the app pool.

  • I also had to import the local host certificate into my personal store using mmc.exe.

My web.config file was already configured correctly, so after I got all the above sorted out, I was able to continue my testing.

Solution 16 - C#

My solution (VB.Net, the "staging" (UAT) version of this application needs to work with the "staging" certificate but not affect requests once they are on the live site):

    ...
        Dim url As String = ConfigurationManager.AppSettings("APIURL") & "token"
        If url.ToLower().Contains("staging") Then
           System.Net.ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications
        End If
    ...

    Private  Function AcceptAllCertifications(ByVal sender As Object, ByVal certification As System.Security.Cryptography.X509Certificates.X509Certificate, ByVal chain As System.Security.Cryptography.X509Certificates.X509Chain, ByVal sslPolicyErrors As System.Net.Security.SslPolicyErrors) As Boolean
        Return True
    End Function

Solution 17 - C#

A variation I've been using for a while it if helps anyone.

The caller has to explicitly request that untrusted certifications are required and places the callback back into it's default state upon completion.

	/// <summary>
	/// Helper method for returning the content of an external webpage
	/// </summary>
	/// <param name="url">URL to get</param>
	/// <param name="allowUntrustedCertificates">Flags whether to trust untrusted or self-signed certificates</param>
	/// <returns>HTML of the webpage</returns>
	public static string HttpGet(string url, bool allowUntrustedCertificates = false) {
		var oldCallback = ServicePointManager.ServerCertificateValidationCallback;
		string webPage = "";
		try {
			WebRequest req = WebRequest.Create(url);

			if (allowUntrustedCertificates) {
				// so we can query self-signed certificates
				ServicePointManager.ServerCertificateValidationCallback = 
					((sender, certification, chain, sslPolicyErrors) => true);
			}

			WebResponse resp = req.GetResponse();
		
			using (StreamReader sr = new StreamReader(resp.GetResponseStream())) {
				webPage = sr.ReadToEnd().Trim();
				sr.Close();
			}
			return webPage;
		}
		catch {
			// if the remote site fails to response (or we have no connection)
			return null;
		}
		finally {
			ServicePointManager.ServerCertificateValidationCallback = oldCallback;
		}
	}

Solution 18 - C#

Actualy this issue coming in SSL/TLS Certificate Issue so you can find issue using following Code:

Here is best solution https://indiabix.info/id/16/the-underlying-conne

Solution 19 - C#

If not work bad sertificate, when ServerCertificateValidationCallback return true; My ServerCertificateValidationCallback code:

ServicePointManager.ServerCertificateValidationCallback += delegate
{
    LogWriter.LogInfo("Проверка сертификата отключена, на уровне ServerCertificateValidationCallback");
    return true;
};

My code which the prevented execute ServerCertificateValidationCallback:

     if (!(ServicePointManager.CertificatePolicy is CertificateValidation))
    {
        CertificateValidation certValidate = new CertificateValidation();
        certValidate.ValidatingError += new CertificateValidation.ValidateCertificateEventHandler(this.OnValidateCertificateError);
        ServicePointManager.CertificatePolicy = certValidate;
    }

OnValidateCertificateError function:

private void OnValidateCertificateError(object sender, CertificateValidationEventArgs e)
{
	string msg = string.Format(Strings.OnValidateCertificateError, e.Request.RequestUri, e.Certificate.GetName(), e.Problem, new Win32Exception(e.Problem).Message);
	LogWriter.LogError(msg);
	//Message.ShowError(msg);
}

I disabled CertificateValidation code and ServerCertificateValidationCallback running very well

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRob SchripsemaView Question on Stackoverflow
Solution 1 - C#Sebastian CastaldiView Answer on Stackoverflow
Solution 2 - C#RemyView Answer on Stackoverflow
Solution 3 - C#Marc GravellView Answer on Stackoverflow
Solution 4 - C#cusmanView Answer on Stackoverflow
Solution 5 - C#Gregor SlavecView Answer on Stackoverflow
Solution 6 - C#DiogoView Answer on Stackoverflow
Solution 7 - C#sipsorceryView Answer on Stackoverflow
Solution 8 - C#HansView Answer on Stackoverflow
Solution 9 - C#Chris - Haddox TechnologiesView Answer on Stackoverflow
Solution 10 - C#debiasejView Answer on Stackoverflow
Solution 11 - C#Manuel RoldanView Answer on Stackoverflow
Solution 12 - C#Amir-ranjbarView Answer on Stackoverflow
Solution 13 - C#Thomas KoelleView Answer on Stackoverflow
Solution 14 - C#ErnestView Answer on Stackoverflow
Solution 15 - C#PopoView Answer on Stackoverflow
Solution 16 - C#GreenRockView Answer on Stackoverflow
Solution 17 - C#toepoke.co.ukView Answer on Stackoverflow
Solution 18 - C#Sachin SrivastavaView Answer on Stackoverflow
Solution 19 - C#Roberto GataView Answer on Stackoverflow