Using X509Certificates to secure WCF services - wcf

The scenario I am working on involves an ASP.NET web application communicating with a self-hosted WCF service with a netTcpBinding. The two components are hosted on separate machines. The web server is a stand-alone machine in a DMZ with no trust relationship with the application server.
I want the communication to be secured at transport level. As I understand if both the client and the app server have suitable X509 certificates installed, they can authenticate to each other, and the data exchange can also be encrypted.
I have provisioned the a web server with a ClientAuthentication certificate, and the app server with a ServerAuthentication certificate. In each case, the certificates are stored in the LocalMachine\My store. I have ensured that Private Keys are available for all certificates, and that the app pool identity and the BUILTIN\LOCAL identities (on the web and app server respectively) have full access to the private keys. I have also copied the public key part of the certificates (i.e. .cer files) to the LocalMachine\TrustedPeople store on the opposite server.
The configuration looks like this:
App server
<services>
<service behaviorConfiguration="DefaultServiceBehavior" name="Evs.Application.Services.XXXXXProvider">
<endpoint address="net.tcp://localhost:8000/Evs.Application.Services/XXXXXServiceCert"
binding="netTcpBinding" bindingConfiguration="SecureCertificateNetTcpBinding" contract="Evs.Application.Contracts.IXXXXXProvider"
behaviorConfiguration="endpointBehavior"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="DefaultServiceBehavior">
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceCredentials>
<serviceCertificate storeLocation="LocalMachine" storeName="My" x509FindType="FindByThumbprint" findValue="xxxxxxxxxxxxxx"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<binding name="SecureNetTcpBinding">
<security mode="Transport" />
</binding>
<binding name="SecureCertificateNetTcpBinding">
<security mode="Transport">
<transport clientCredentialType="Certificate" />
</security>
</binding>
</netTcpBinding>
</bindings>
Web server
<client>
<endpoint address="net.tcp://app-ext-01.prod.mydomain.com:8000/Evs.Application.Services/XXXXXServiceCert"
behaviorConfiguration="secureEndPointBehaviour" binding="netTcpBinding"
bindingConfiguration="SecureCertificateNetTcpBinding" contract="Evs.Application.Contracts.IXXXXXProvider"
name="XXXXXProvider"/>
<client>
<behaviors>
<endpointBehaviors>
<behavior name="secureEndPointBehaviour">
<clientCredentials>
<clientCertificate findValue= "xxxxxxxxxxxxxxxxxxx"
storeLocation="LocalMachine" storeName="My"
x509FindType="FindByThumbprint"/>
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<netTcpBinding>
<binding name="SecureCertificateNetTcpBinding">
<security mode="Transport">
<transport clientCredentialType="Certificate" />
</security>
</binding>
</netTcpBinding>
</bindings>
In the staging environment that I have for testing this, a call to the service fails with the exception below (retrieved from server-side logs)
System.ServiceModel.CommunicationException: The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:00:59.9840000'. ---&gt; System.IO.IOException: The read operation failed, see inner exception. ---&gt;
System.ServiceModel.CommunicationException: The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:00:59.9840000'. ---&gt; System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.ServiceModel.Channels.SocketConnection.ReadCore(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout, Boolean closing)
--- End of inner exception stack trace ---
at System.ServiceModel.Channels.SocketConnection.ReadCore(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout, Boolean closing)
at System.ServiceModel.Channels.SocketConnection.Read(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout)
at System.ServiceModel.Channels.ConnectionStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.Security._SslStream.StartFrameHeader(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security._SslStream.StartReading(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
--- End of inner exception stack trace ---
at System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.ServiceModel.Channels.StreamConnection.Read(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout)
--- End of inner exception stack trace ---
Can anyone suggest what I need to do to this configuration to get it working?

I believe you're missing:
Server-Side
<serviceCredentials>
<clientCertificate>
<authentication certificateValidationMode="PeerTrust" />
</clientCertificate>
</serviceCredentials>
Client-Side
<clientCredentials>
<serviceCertificate>
<authentication certificateValidationMode="PeerTrust" />
</serviceCertificate>
</clientCredentials>

Related

WCF NetMessagingBinding and Outgoing Quotas

I'm trying to use WCF and NetMessagingBinding to publish messages into a Windows Service Service Bus Topic and for large messages - at least 603kb - the push operation is throwing the following error:
System.ServiceModel.QuotaExceededException: The maximum message size quota for outgoing messages (262144) has been exceeded.
Server stack trace:
at System.Runtime.BufferedOutputStream.WriteCore(Byte[] buffer, Int32 offset, Int32 size)
at System.Xml.XmlBinaryNodeWriter.FlushBuffer()
at System.Xml.XmlStreamNodeWriter.GetBuffer(Int32 count, Int32& offset)
at System.Xml.XmlStreamNodeWriter.UnsafeWriteUTF8Chars(Char* chars, Int32 charCount)
at System.Xml.XmlBinaryNodeWriter.UnsafeWriteText(Char* chars, Int32 charCount)
at System.Xml.XmlBinaryNodeWriter.WriteText(String value)
at System.Xml.XmlBaseWriter.WriteString(String value)
(...)
From the error I noticed that the problem is not the serialization and therefore I can't use a Message Formatter. What else can I use to overcome this exception? Any thoughts?
Thanks in advance!
This issue was solved by replacing the netMessagingBinding by a customBinding which uses the netMessagingTransport.
1- Add netMessagingTransport as a binding extension:
<bindingElementExtensions>
<add name="netMessagingTransport" type="Microsoft.ServiceBus.Messaging.Configuration.NetMessagingTransportExtensionElement, Microsoft.ServiceBus, Version=1.8.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</bindingElementExtensions>
2- Add a custom binding:
<customBinding>
<binding name="sbBindingConfiguration" sendTimeout="00:01:00" receiveTimeout="00:01:00" openTimeout="00:01:00">
<binaryMessageEncoding>
<readerQuotas maxDepth="100000000" maxStringContentLength="100000000"
maxArrayLength="100000000" maxBytesPerRead="100000000" maxNameTableCharCount="100000000"/>
</binaryMessageEncoding>
<netMessagingTransport manualAddressing="false" maxBufferPoolSize="100000" maxReceivedMessageSize="100000000">
<transportSettings batchFlushInterval="00:00:00"/>
</netMessagingTransport>
</binding>
</customBinding>
3- Use the attribute maxReceivedMessageSize to define a value that suits the size of messages that will be exchanged
4- Reference your custom binding in the endpoint
<endpoint (...) binding="customBinding" bindingConfiguration="sbBindingConfiguration" />

Constant "System.ServiceModel.EndpointNotFoundException: There was no endpoint listening at <Service URL>" errors

I have a number of WCF services, running on IIS on a dedicated server. These services have their clients. All in all it works, but whenever I look up the logs at the client-level, I usually see these kind of errors:
System.ServiceModel.EndpointNotFoundException: There was no endpoint listening at <Service URL> that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
---> System.Net.WebException: Unable to connect to the remote server
---> System.Net.Sockets.SocketException: A socket operation was attempted to an unreachable network <Service IP>:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at System.ServiceModel.Channels.HttpOutput.WebRequestHttpOutput.GetOutputStream()
--- End of inner exception stack trace ---
Server stack trace:
at System.ServiceModel.Channels.HttpOutput.WebRequestHttpOutput.GetOutputStream()
at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.SendRequest(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.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.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
But right after that this same program would send requests that would work correctly.
This is the configuration of the WCF Service:
<netTcpBinding>
<binding name="config" closeTimeout="0:5:0" openTimeout="0:5:0" sendTimeout="0:5:0" receiveTimeout="0:5:0"
maxBufferPoolSize="8388608" maxBufferSize="8388608" maxReceivedMessageSize="8388608" maxConnections="8388608">
<readerQuotas maxArrayLength="8388608" maxNameTableCharCount="8388608" maxStringContentLength="8388608"/>
<security mode="None"/>
</binding>
</netTcpBinding>
and
<basicHttpBinding>
<binding name="config2" closeTimeout="0:5:0" openTimeout="0:5:0" sendTimeout="0:5:0" receiveTimeout="0:5:0"
maxBufferPoolSize="838860800" maxBufferSize="838860800" maxReceivedMessageSize="838860800">
<readerQuotas maxArrayLength="838860800" maxNameTableCharCount="838860800" maxStringContentLength="838860800"/>
<security mode="None"/>
</binding>
</basicHttpBinding>
Service behavior:
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="false"/>
<!-- 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"/>
<dataContractSerializer maxItemsInObjectGraph="838860800"/>
</behavior>
I think there may be a limit somewhere for the number of simultaneous connections. Or maybe its something in IIS settings or something in the WCF service configuration. But I can't find what and where.
Also, the NetTcpBinding configuration has a property MaxConnection, but basicHttpBinding does not.
Thanks a lot in advance for your help!
Following is the solved version of my own Web.config (Suitable for my project). Useful hints may be picked from the following working sample. -- Sujayyendhiren
<service name="WelcomeSOAPXMLService">
<endpoint address="http://localhost:16672/Service.svc" binding="basicHttpBinding" contract="IWelcomeSOAPXMLService"/>

HTTP 400 Bad Request Error with WCF Service when message size exceeds 64K

I have a .NET 4.0 WCF service. If I send a soap message larger than 64K, then I get "The remote server returned an unexpected response: (400) Bad Request" Error. It works fine all the way until I go over the 64K message size. I have read the many posts out there regarding what to do for this error, and as far as I can tell, I have the correct web.config values, but I still get the error. Below are the settings in my web.config. Anything I am missing? This occurs when communicating both to my local ASP.NET VS server and a remote Windows 2008 R2 IIS server. Is there a way to verify or log the maxReceivedMessageSize settings, etc. that are in the service binding in real-time or in the debugger? The service is hosted in MVC if that makes any difference.
<httpRuntime maxRequestLength="50000000" />
...
...
<bindings>
<basicHttpBinding>
<binding name="IpsApiBinding" receiveTimeout="00:15:00" sendTimeout="00:05:00" maxReceivedMessageSize="40000000">
<readerQuotas maxDepth="5000000" maxStringContentLength="50000000"
maxArrayLength="50000000" maxBytesPerRead="50000000" />
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="ApiBehavior" name="IPSApi.IpsApi">
<endpoint behaviorConfiguration="endpointBehavior" binding="basicHttpBinding"
bindingConfiguration="IpsApiBinding" name="IPSApi.IpsApi"
contract="IPSApi.IIPSApi" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="endpointBehavior">
<dataContractSerializer maxItemsInObjectGraph="6553600" />
<callbackDebug includeExceptionDetailInFaults="true" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ApiBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
On the client side, the stack track is showing...
Server stack trace: at
System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest
request, HttpWebResponse response, HttpChannelFactory factory,
WebException responseException, ChannelBinding channelBinding) at
System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan
timeout) at
System.ServiceModel.Channels.RequestChannel.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) ...
I figured out my problem. Here are the details. I am hosting my WCF service in a MVC app. The WCF service is in a separate DLL. I had the configuration settings in the web.config thinking that it would read its config from there. Come to find out, if in a separate DLL, then it will not use the web.config settings. It was just using the default bindings, etc.
To get it to read the configuration in web.config, I used the method that was suggested in http://blogs.msdn.com/b/dotnetinterop/archive/2008/09/22/custom-service-config-file-for-a-wcf-service-hosted-in-iis.aspx . I created my own custom ServiceHostFactory and ServiceHost. In the ServiceHostFactory.CreateServiceHost I create an instance of my ServiceHost (derived class). In my ServiceHost derived class, I take over the ApplyConfiguration and load the config from the web.config.
It works!
I had a similar issue and also had to increase two additional fields on the binding that I do not see in your code... maxBufferSize and maxBufferPoolSize. Not sure if this would be your issue but I know that the default for these is roughly 64k.
Sample Web.config settings:
<binding name="HTTPNoneBinding" closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:10:00" allowCookies="false"
bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
I would suggest for to enable Tracing on your Service to determine the exact cause of the Bad Request. If it is because of the message size the framework would tell you clearly on which property needs to be set. In order to enable tracing follow this link

TimeoutException thrown by a WCF client proxy

My question is related to a System.TimeoutException that is thrown by WCF from time to time:
System.TimeoutException: The open
operation did not complete within the
allotted timeout of 00:00:00. The time
allotted to this operation may have
been a portion of a longer timeout.
---> System.TimeoutException: Open timed out after 00:00:00 while
establishing a transport session to
net.tcp://192.168.1.100:50000/TabletSvc/.
The time allotted to this operation
may have been a portion of a longer
timeout. ---> System.TimeoutException:
Connecting to via
net.tcp://192.168.1.100:50000/TabletSvc/
timed out after 00:00:00. Connection
attempts were made to 0 of 1 available
addresses (). Check the RemoteAddress
of your channel and verify that the
DNS records for this endpoint
correspond to valid IP Addresses. The
time allotted to this operation may
have been a portion of a longer
timeout.
What are the possible causes for random behavior?
The WCF service is hosted into a .NET application running on Windows XP SP2. The application creates a client proxy to same service hosted on a different machine. One important aspect is that the service is using reliableSession and serviceThrottling. The machines are communicating through a WiFi connection.
The client and the service are on separate threads inside the same application. From this point of view they do not depend on each other. There should be no locking.
I checked the WiFi connectivity between machines using ping and it appears to be fine. The next step would be to put in place a network monitor, but since they are production machines it might not happen soon.
I thought about increasing both maxConcurrentSessions and maxConcurrentInstances to 50 but haven't got the time to test it. This is based on the idea that maybe the application is running out of resources or reaches a limit which impacts the hosted service.
As I said, the client proxy fails to open a connection only from time to time. A second attempt a minute later usually succeeds.
Here is the client and service configuration:
<system.serviceModel>
<client>
<endpoint name="TabletSvcEndpoint" address="net.tcp://localhost:50000/TabletSvc/" binding="netTcpBinding" bindingConfiguration="TabletSvcBinding" contract="ITabletSvc">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</client>
<services>
<service behaviorConfiguration="TabletSvcBehavior" name="TabletSvc">
<endpoint name="TabletSvcEndpoint" address="" binding="netTcpBinding" bindingConfiguration="TabletSvcBinding" contract="ITabletSvc">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:50000/TabletSvc/" />
</baseAddresses>
</host>
</service>
</services>
<bindings>
<netTcpBinding>
<binding name="TabletSvcBinding" receiveTimeout="00:30:00" sendTimeout="00:00:30" closeTimeout="00:00:05" openTimeout="00:00:05" transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions" hostNameComparisonMode="StrongWildcard" listenBacklog="10" maxBufferPoolSize="524288" maxBufferSize="6553600" maxConnections="10" maxReceivedMessageSize="6553600">
<readerQuotas maxDepth="32" maxStringContentLength="819200" maxArrayLength="163840" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession inactivityTimeout="00:01:00" ordered="true" enabled="true" />
<security mode="None" />
</binding>
</netTcpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="TabletSvcBehavior">
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceThrottling maxConcurrentSessions="10" maxConcurrentInstances="10" maxConcurrentCalls="100" />
</behavior>
</serviceBehaviors>
</behaviors>
<diagnostics performanceCounters="Off" wmiProviderEnabled="False" >
<messageLogging maxMessagesToLog="250" logEntireMessage="true" logMessagesAtServiceLevel="true" logMalformedMessages="true" logMessagesAtTransportLevel="true" />
</diagnostics>
</system.serviceModel>
Here is the stack trace of the exception:
10:20:18.3125 ClientChannel: Opening
10:20:48.8437 ClientChannel: Faulted
10:20:48.8593 Error: System.TimeoutException: The open operation did not complete within the allotted timeout of 00:00:00. The time allotted to this operation may have been a portion of a longer timeout. ---> System.TimeoutException: Open timed out after 00:00:00 while establishing a transport session to net.tcp://192.168.1.100:50000/TabletSvc/. The time allotted to this operation may have been a portion of a longer timeout. ---> System.TimeoutException: Connecting to via net.tcp://192.168.1.100:50000/TabletSvc/ timed out after 00:00:00. Connection attempts were made to 0 of 1 available addresses (). Check the RemoteAddress of your channel and verify that the DNS records for this endpoint correspond to valid IP Addresses. The time allotted to this operation may have been a portion of a longer timeout.
at System.ServiceModel.Channels.SocketConnectionInitiator.CreateTimeoutException(Uri uri, TimeSpan timeout, IPAddress[] addresses, Int32 invalidAddressCount, SocketException innerException)
at System.ServiceModel.Channels.SocketConnectionInitiator.Connect(Uri uri, TimeSpan timeout)
at System.ServiceModel.Channels.BufferedConnectionInitiator.Connect(Uri uri, TimeSpan timeout)
at System.ServiceModel.Channels.TracingConnectionInitiator.Connect(Uri uri, TimeSpan timeout)
at System.ServiceModel.Channels.ConnectionPoolHelper.EstablishConnection(TimeSpan timeout)
--- End of inner exception stack trace ---
at System.ServiceModel.Channels.ConnectionPoolHelper.EstablishConnection(TimeSpan timeout)
at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.OnOpen(TimeSpan timeout)
--- End of inner exception stack trace ---
Server stack trace:
at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ReliableChannelBinder`1.ChannelSynchronizer.SyncWaiter.TryGetChannel()
at System.ServiceModel.Channels.ReliableChannelBinder`1.ChannelSynchronizer.SyncWaiter.TryWait(TChannel& channel)
at System.ServiceModel.Channels.ReliableChannelBinder`1.ChannelSynchronizer.TryGetChannel(Boolean canGetChannel, Boolean canCauseFault, TimeSpan timeout, MaskingMode maskingMode, TChannel& channel)
at System.ServiceModel.Channels.ReliableChannelBinder`1.Send(Message message, TimeSpan timeout, MaskingMode maskingMode)
at System.ServiceModel.Channels.SendReceiveReliableRequestor.OnRequest(Message request, TimeSpan timeout, Boolean last)
at System.ServiceModel.Channels.ReliableRequestor.Request(TimeSpan timeout)
at System.ServiceModel.Channels.ClientReliableSession.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ClientReliableDuplexSessionChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
at System.ServiceModel.Channels.ServiceChannel.EnsureOpened(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)
I had this issue too. I had resolved it with replacement of "Localhost" by "127.0.0.1".
NET application running on Windows XP SP2
Note: For Windows XP Professional, the maximum number of other computers that are permitted to simultaneously connect over the network is ten. This limit includes all transports and resource sharing protocols combined. For Windows XP Home Edition, the maximum number of other computers that are permitted to simultaneously connect over the network is five.
Microsoft KB
Also add this to your app/web.config
<system.net>
<connectionManagement>
<add address="*" maxconnection="5000" />
</connectionManagement>
</system.net>
Microsoft never meant for the network stack in XP to handle so many connections...

Deploying WCF Service in Windows Service with pipes getting 'System.ServiceModel.Security.SecurityNegotiationException'

We've created a WCF service that is hosted as a Windows Service. Our service is installed with our application on a computer, and it will never be accessed remotely from other clients. So, we've designed it to use named pipes... On our development computer, it works perfectly when we install and run our service and application. However, when we deploy our application and service to a test computer and run it, we get an SecurityNegotiationException, which is due to a call that our application makes to the service when it launches. If I comment out this service call, our application loads and run properly, as long as it doesn't use the service. I've scoured the Internet to see how to resolve this issue, but I couldn't find anything that deals specifically with WCF + Windows Service + named pipes. I really would appreciate your help!
Thanks,
Mike
EXCEPTION
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.ServiceModel.Security.SecurityNegotiationException
Stack:
Server stack trace:
at System.ServiceModel.Channels.WindowsStreamSecurityUpgradeProvider.WindowsStreamSecurityUpgradeInitiator.OnInitiateUpgrade(Stream stream, SecurityMessageProperty& remoteSecurity)
at System.ServiceModel.Channels.StreamSecurityUpgradeInitiatorBase.InitiateUpgrade(Stream stream)
at System.ServiceModel.Channels.ConnectionUpgradeHelper.InitiateUpgrade(StreamUpgradeInitiator upgradeInitiator, IConnection& connection, ClientFramingDecoder decoder, IDefaultCommunicationTimeouts defaultTimeouts, TimeoutHelper& timeoutHelper)
at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.SendPreamble(IConnection connection, ArraySegment`1 preamble, TimeoutHelper& timeoutHelper)
at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.DuplexConnectionPoolHelper.AcceptPooledConnection(IConnection connection, TimeoutHelper& timeoutHelper)
at System.ServiceModel.Channels.ConnectionPoolHelper.EstablishConnection(TimeSpan timeout)
at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
at System.ServiceModel.Channels.ServiceChannel.EnsureOpened(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
at ClientSaver.MainForm..ctor()
at ClientSaver.Program.Main()
=========================================================
SERVICE'S APP.CONFIG FILE
<system.serviceModel>
<services>
<service behaviorConfiguration="" name="ClientSaver.VssService.VssService">
<endpoint address="Pipe" binding="netNamedPipeBinding"
bindingConfiguration="" contract="ClientSaver.VssService.IVssService" />
<host>
<baseAddresses>
<add baseAddress="net.pipe://localhost/VssService/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
===========================================================
=== CLIENT'S WCF INFORMATION FROM ITS APP.CONFIG ==
<bindings>
<netNamedPipeBinding>
<binding name="NetNamedPipeBinding_IVssService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288"
maxBufferSize="65536" maxConnections="10" maxReceivedMessageSize="65536">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="Transport">
<transport protectionLevel="EncryptAndSign" />
</security>
</binding>
</netNamedPipeBinding>
</bindings>
<client>
<endpoint address="net.pipe://localhost/VssService/Pipe" binding="netNamedPipeBinding"
bindingConfiguration="NetNamedPipeBinding_IVssService" contract="VssService.IVssService"
name="NetNamedPipeBinding_IVssService">
<identity>
<servicePrincipalName value="host/DEVPC_W7.aboh.local" />
</identity>
</endpoint>
</client>
<services>
<service name="ClientSaver.VssService.VssService">
<endpoint address="net.pipe://localhost" binding="netNamedPipeBinding"
bindingConfiguration="" contract="ClientSaver.VssService.IVssService" />
<endpoint address="http://localhost/VssService/" binding="basicHttpBinding"
bindingConfiguration="" contract="ClientSaver.VssService.IVssService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="VssServiceBehavior">
<serviceMetadata httpGetEnabled="true" policyVersion="Policy15" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
When using the NetNamedPipeBinding, Transport security is configured by default. This causes a security negotiation between the client and service channel stacks when the channel is opened. Your exception is occurring during initiation of this negotiation. (See here for more detail on how this happens.)
Please could you provide details of how your WCF client is configured. The value of the exception's Message property would also be valuable diagnostic information. My guess is that there is some mismatch between the configuration of security on the client side and the default configuration shown for the Service.
The named pipe binding is used only for in-proc service / client. It means that the service and the client must be on the same computer.
Try to use TcpBinding instead if you have both the client and the service developed with WCF.