.NET Framework Bookmark and Share   
 index > Windows Communication Foundation > Could not establish trust relationship for the SSL/TLS secure channel with authority PC1
 

Could not establish trust relationship for the SSL/TLS secure channel with authority PC1

i m using WCF service hosted on IIS with https enabled with a self-signed certificate. the problem is that when i open my WCF Service svc file in IE i warn me about not a trusted certificate but with a warning it establish connection to server. but when i m trying to access the WCF service using code it gives me the exception below:
please help me out of this problem, do i need Trusted signed certificate for my development version or there is something wrong with the configuration of WCF?

System.ServiceModel.Security.SecurityNegotiationException was unhandled
Message="Could not establish trust relationship for the SSL/TLS secure channel with authority 'PC1'."
Source="mscorlib"
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at ConsoleApplication1.ServiceReference1.IService1.GetData(Int32 value)
at ConsoleApplication1.ServiceReference1.Service1Client.GetData(Int32 value) in C:\Documents and Settings\Shaikh\My Documents\Visual Studio 2008\Projects\WCFServiceSecurity\ConsoleApplication1\Service References\ServiceReference1\Reference.cs:line 50
at ConsoleApplication1.Program.Main(String[] args) in C:\Documents and Settings\Shaikh\My Documents\Visual Studio 2008\Projects\WCFServiceSecurity\ConsoleApplication1\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(Assembly 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)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Net.WebException
Message="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 System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
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)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.TlsStream.CallProcessAuthentication(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.ConnectStream.WriteHeaders(Boolean async)
InnerException:



Web.Config of The WCF Service is

<system.serviceModel>
<diagnostics>
<messageLogging logEntireMessage="true" maxMessagesToLog="300" logMessagesAtServiceLevel="false" logMalformedMessages="true" logMessagesAtTransportLevel="true"/>
</diagnostics>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_BulkData" maxReceivedMessageSize="524288000">
<readerQuotas maxDepth="32" maxStringContentLength="5242880" maxArrayLength="5242880"/>
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName"/>

</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="WcfServiceLibrary.Service1" behaviorConfiguration="WcfServiceLibrary.Service1Behavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8731/Design_Time_Addresses/WcfServiceLibrary/Service1/"/>
</baseAddresses>
</host>
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_BulkData" contract="WcfServiceLibrary.IService1">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<!-- Metadata Endpoints -->
<!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. -->
<!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WcfServiceLibrary.Service1Behavior">
<!-- To avoid disclosing metadata information,
set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="True"/>
<!-- To receive exception details in faults for debugging purposes,
set the value below to true. Set to false before deployment
to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="False"/>
<serviceCredentials>
<userNameAuthentication customUserNamePasswordValidatorType="WcfServiceLibrary.CustomUserNamePasswordValidator,WcfServiceLibrary" userNamePasswordValidationMode="Custom"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>



and the code i am using to access the service is

ServiceReference1.Service1Client client = new ConsoleApplication1.ServiceReference1.Service1Client();


client.ClientCredentials.UserName.UserName = "shoaib";
client.ClientCredentials.UserName.Password = "shaikh";

Console.WriteLine(client.GetData(123));//exception occurs here.


ShoaibShaikh

Hi,

I had this one as well, the solution I think what is hapenning is that the WCF client is being asked if is should trust the certificate, and the default bahaviour is to say no.

If this is the case, there are a couple of ways to solve the issue:

1) Override the client cert using the following code:

Imports System.Net
Imports System.Net.Security
Imports System.Security.Cryptography.X509Certificates

Public Class TestUtils

Public Shared Sub OverrideCertificateValidation()
ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf RemoteCertValidate)
End Sub

Private Shared Function RemoteCertValidate(ByVal sender As Object, ByVal cert As X509Certificate, ByVal chain As X509Chain, ByVal [error] As System.Net.Security.SslPolicyErrors) As Boolean
Return True
End Function
End Class

(Sorry for the VB, i'm in a VB project right now).

This tells the client to accept the testcertificate.

2) Install a root certificate authority on both the client and server boxes:

http://www.codeplex.com/WCFSecurity/Wiki/View.aspx?title=How%20To%20-%20Create%20and%20Install%20Temporary%20Certificates%20in%20WCF%20for%20Message%20Security%20During%20Development&referringTitle=How%20Tos

It's hard work getting your head around WCF security. A month ago i knew nothing, now i just about know enough to get by.

There's a great resource on all things WCF Security related here:

http://www.codeplex.com/WCFSecurity

Regards,

Alan

Alan Smith MVP
Shoaib,

Have you found a solution to your problem yet? I'm having the same problem.


tele-bird

Hi,

I had this one as well, the solution I think what is hapenning is that the WCF client is being asked if is should trust the certificate, and the default bahaviour is to say no.

If this is the case, there are a couple of ways to solve the issue:

1) Override the client cert using the following code:

Imports System.Net
Imports System.Net.Security
Imports System.Security.Cryptography.X509Certificates

Public Class TestUtils

Public Shared Sub OverrideCertificateValidation()
ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf RemoteCertValidate)
End Sub

Private Shared Function RemoteCertValidate(ByVal sender As Object, ByVal cert As X509Certificate, ByVal chain As X509Chain, ByVal [error] As System.Net.Security.SslPolicyErrors) As Boolean
Return True
End Function
End Class

(Sorry for the VB, i'm in a VB project right now).

This tells the client to accept the testcertificate.

2) Install a root certificate authority on both the client and server boxes:

http://www.codeplex.com/WCFSecurity/Wiki/View.aspx?title=How%20To%20-%20Create%20and%20Install%20Temporary%20Certificates%20in%20WCF%20for%20Message%20Security%20During%20Development&referringTitle=How%20Tos

It's hard work getting your head around WCF security. A month ago i knew nothing, now i just about know enough to get by.

There's a great resource on all things WCF Security related here:

http://www.codeplex.com/WCFSecurity

Regards,

Alan

Alan Smith MVP
Alan Smith MVP is right i tried the 2nd way he defined to solve this problem i was using verisign's signed certificate and i just install root certificate in my client machine and server machine and then its working fine for me.

ShoaibShaikh

Also the clients identity

<certificate encodedValue="certdatagoeshere"

has to match the SSL certificate used on the IIS server for SSL. So export that certificate into a .cer file. Open that file in notepad and paste the data in for the encoded Value.

TomAndJerry
I found better solution for 1) Override the client cert
I used the following code:

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

  • Proposed As Answer byGolovchenko Monday, December 08, 2008 2:00 PM
  •  
Golovchenko
Thanks Golovchenko, That one line of code really did the trick for me. I was using WsHttp binding for Transport Security in Self hosted WCF service.
  • Proposed As Answer bySynDev Wednesday, January 21, 2009 9:36 PM
  •  
SynDev
Worked for me too. BasicHttpBinding with security enabled using a self-signed certificate.
George Ivanov
I just learnt another way to get around this problem that may be better than simply trusting every cert.

Open C:\WINDOWS\system32\drivers\etc\hosts in notepad.

At the bottom of that file you should probably see:

127.0.0.1 localhost

What you can do is add the ip address of the server and the certificate name, like this:

172.1.1.1 serverKeyName

Save and close the 'hosts' file.

Now in your app.config, change the endpoint address
from: https://172.1.1.1:port /fooService
to: https://serverKeyName:port /fooService

You will also need to install the certificate, just put the url of the service into IE and you should be prompted to install (during the install you can click 'Details' to determine the certificate name).

Once you have done that your machine should now trust that server. Worked for me and now I don't have to remember to remove the code that trusts everything :-)
wallism
I found better solution for 1) Override the client cert
I used the following code:

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

I'm running into the same error and have not worked much with WCF before. Where do you put this line of code? In the page calling the service, the global.asax or somewhere else? Thanks.
gswartz

You can use google to search for other answers

Custom Search

More Threads

• Windows Service and Named pipe issue
• SoapException: Server did not recognize the value of HTTP Header SOAPAction:
• Chunking Binding with Dual TCP
• multiple WCF service instances with different parameters
• FaultException faulting the channel
• Is a CommunicationObjectAbortedException handled by reliable sessions?
• WS-Addressing mandatory with WS-Secure Conversation?
• what's wrong with my wsDualhttpBinding config.
• An error occured when verifying security for the message
• Works on local, but fails when calling remote WCF (hosted on IIS).