Set the MaxClockSkew when using NetTcpBinding with TransportWithMessageCredential - c#

I'm using WCF with the NetTcpBinding and I'm unable to set the MaxClockSkew as the SymmetricSecurityBindingElement is null when using SecurityMode of TransportWithMessageCrediential. Does anyone know how this is done when using TransportWithMessageCrediential SecurityMode?
private Binding GetNetTcpBinding()
{
long MaxReceivedMessageSize = 2147483647;
int MaxStringContentLength = 2147483647;
int MaxBytesPerRead = 2147483647;
int MaxNameTableCharCount = 100000;
var timeout = 5;
var maxClockSkew = new TimeSpan(0, 30, 0);
var binding = new NetTcpBinding
{
OpenTimeout = new TimeSpan(0, 0, timeout),
SendTimeout = new TimeSpan(0, 0, timeout),
ReceiveTimeout = new TimeSpan(0, 0, timeout),
MaxReceivedMessageSize = MaxReceivedMessageSize,
ReaderQuotas = new XmlDictionaryReaderQuotas
{
MaxArrayLength = MaxBytesPerRead,
MaxBytesPerRead = MaxBytesPerRead,
MaxNameTableCharCount = MaxNameTableCharCount,
MaxStringContentLength = MaxStringContentLength,
MaxDepth = MaxBytesPerRead
}
};
binding.ReliableSession = new OptionalReliableSession
{
Enabled = true,
InactivityTimeout = new TimeSpan(0, 0, timeout),
Ordered = true
};
binding.Security = new NetTcpSecurity
{
Mode = SecurityMode.TransportWithMessageCredential,
Message = new MessageSecurityOverTcp
{
ClientCredentialType = MessageCredentialType.Certificate,
AlgorithmSuite = SecurityAlgorithmSuite.Basic256
},
Transport = new TcpTransportSecurity
{
ClientCredentialType = TcpClientCredentialType.Certificate,
SslProtocols = SslProtocols.Tls12
}
};
var customBinding = new CustomBinding(binding);
var security =
customBinding.Elements.Find<SymmetricSecurityBindingElement>();
// NOTE: This Always Returns NULL
if (security != null)
{
security.LocalClientSettings.MaxClockSkew = maxClockSkew;
security.LocalServiceSettings.MaxClockSkew = maxClockSkew;
// Get the System.ServiceModel.Security.Tokens.SecureConversationSecurityTokenParameters
var secureTokenParams =
(SecureConversationSecurityTokenParameters)security.ProtectionTokenParameters;
// From the collection, get the bootstrap element.
var bootstrap = secureTokenParams.BootstrapSecurityBindingElement;
// Set the MaxClockSkew on the bootstrap element.
bootstrap.LocalClientSettings.MaxClockSkew = maxClockSkew;
bootstrap.LocalServiceSettings.MaxClockSkew = maxClockSkew;
return customBinding;
}
return binding;
}
I'm unable to find any solutions for this and the documentation seems to be out of date. This only works if you use SecurityMode.Message.

Related

WCF service run very slow with reliable session

The server is hosted on a WPF application and use net.tcp binding for duplex channel. We have the client (.NET 4.0) to send a burst of async request to the server. After reliable session is on, the service become really slow (approx. 50-100 call/s) and callback messages aren't sent to the client.
The issue happens in two cases.
We send approx. 1000 messages per seconds to the server. If we send 300-500 messages is all OK.
We send a single message to the server with size 10-20 MB. And in this case messages from the server callbacks wait until the big message is sending.
Below are the codes for the server and client.
Server's binding:
(Also we tried to use standart net.tcp binding istead of custom one but it didn't help)
var customBinding= new CustomBinding()
{
CloseTimeout = new TimeSpan(0, 1, 10),
OpenTimeout = new TimeSpan(0, 1, 10),
ReceiveTimeout = new TimeSpan(0, 5, 30),
SendTimeout = new TimeSpan(0, 2, 0)
};
customBinding.Elements.Add(new BinaryMessageEncodingBindingElement()
{
MessageVersion = MessageVersion.Default,
ReaderQuotas =
{
MaxBytesPerRead = int.MaxValue,
MaxDepth = int.MaxValue,
MaxNameTableCharCount = int.MaxValue,
MaxStringContentLength = int.MaxValue,
MaxArrayLength = int.MaxValue
}
});
customBinding.Elements.Add(new ReliableSessionBindingElement()
{
AcknowledgementInterval = TimeSpan.FromMilliseconds(1),
FlowControlEnabled = true,
InactivityTimeout = new TimeSpan(0, 30, 0),
MaxPendingChannels = 1000,
MaxRetryCount = 10,
MaxTransferWindowSize = 4096,
Ordered = true,
ReliableMessagingVersion = ReliableMessagingVersion.Default
});
var tcpTransport = new TcpTransportBindingElement()
{
ChannelInitializationTimeout = TimeSpan.FromSeconds(30),
ConnectionBufferSize =8192,
ListenBacklog = 10000000,
MaxBufferPoolSize = int.MaxValue,
MaxBufferSize = int.MaxValue,
MaxOutputDelay= TimeSpan.FromMilliseconds(1000),
MaxPendingAccepts = int.MaxValue,
MaxPendingConnections = 40000,
MaxReceivedMessageSize = int.MaxValue,
PortSharingEnabled = true,
TransferMode = TransferMode.Buffered,
};
tcpTransport.ConnectionPoolSettings.GroupName = "OnlineList";
tcpTransport.ConnectionPoolSettings.IdleTimeout = TimeSpan.FromMinutes(5);
tcpTransport.ConnectionPoolSettings.LeaseTimeout = TimeSpan.FromMinutes(5);
tcpTransport.ConnectionPoolSettings.MaxOutboundConnectionsPerEndpoint = 40000;
customBinding.Elements.Add(tcpTransport);
Client side configuration:
BaseTimeout = 7000;
int.MaxValue = 2147483647;
///Common
CloseTimeout = new TimeSpan(0, 0, BaseTimeout),
OpenTimeout = new TimeSpan(0, 0, BaseTimeout),
ReceiveTimeout = new TimeSpan(0, 0, BaseTimeout*4),
SendTimeout = new TimeSpan(0, 0, BaseTimeout),
///Security
Security = { Mode = SecurityMode.None },
///Session
ReliableSession =
{
Enabled = true,
InactivityTimeout = new TimeSpan(1, 10, 0),
Ordered = true
},
///Buffer and message
MaxBufferPoolSize = int.MaxValue,
MaxBufferSize = int.MaxValue,
MaxReceivedMessageSize = int.MaxValue,
///ReaderQuotas
ReaderQuotas =
{
MaxBytesPerRead = int.MaxValue,
MaxDepth = int.MaxValue,
MaxNameTableCharCount = int.MaxValue,
MaxStringContentLength = int.MaxValue,
MaxArrayLength = int.MaxValue
},
//Other
PortSharingEnabled = true,
MaxConnections = 1000,
TransactionFlow = true,
TransferMode = TransferMode.Buffered,

WCF Client Sign Soap Message with Smart Card

I have forms application with service reference by using CustomBinding for signing soap request (Only need soap body will be signed). If I try to sign request with private key included pfx wcf client succesfully sign Basic256Sha256Rsa15.
Succesfull case below:
private CustomBinding GetCustomHttpBinding()
{
CustomBinding binding = new CustomBinding();
// Open and Close = 20s
binding.OpenTimeout = new TimeSpan(0, 0, 20);
binding.CloseTimeout = new TimeSpan(0, 0, 20);
// Send and Receive = 300s
binding.SendTimeout = new TimeSpan(0, 5, 0);
binding.ReceiveTimeout = new TimeSpan(0, 5, 0);
// ++ Setting security binding ++
var param = new X509SecurityTokenParameters();
param.X509ReferenceStyle = X509KeyIdentifierClauseType.IssuerSerial;
param.ReferenceStyle = SecurityTokenReferenceStyle.Internal;
param.InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient;
param.RequireDerivedKeys = false;
var userNameToken = new UserNameSecurityTokenParameters();
userNameToken.InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient;
var securityElement = new AsymmetricSecurityBindingElement();
securityElement.EnableUnsecuredResponse = true;
securityElement.IncludeTimestamp = true;
securityElement.RecipientTokenParameters = new X509SecurityTokenParameters(X509KeyIdentifierClauseType.IssuerSerial, SecurityTokenInclusionMode.Never);
securityElement.InitiatorTokenParameters = new X509SecurityTokenParameters(X509KeyIdentifierClauseType.IssuerSerial, SecurityTokenInclusionMode.AlwaysToRecipient);
securityElement.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Basic256Sha256Rsa15;
securityElement.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
securityElement.SetKeyDerivation(false);
securityElement.EndpointSupportingTokenParameters.Signed.Add(param);
//securityElement.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
securityElement.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;
binding.Elements.Add(securityElement);
// ++ Setting message encoding binding ++
var encodingElement = new TextMessageEncodingBindingElement();
encodingElement.MessageVersion = MessageVersion.Soap12;
encodingElement.WriteEncoding = Encoding.UTF8;
//encodingElement.MaxReadPoolSize = 50000000;
//encodingElement.MaxWritePoolSize = 50000000;
encodingElement.ReaderQuotas.MaxArrayLength = 50000000;
encodingElement.ReaderQuotas.MaxStringContentLength = 50000000;
binding.Elements.Add(encodingElement);
// ++ Setting https transport binding ++
var httpsElement = new HttpsTransportBindingElement();
// Messagge buffer size
httpsElement.MaxBufferSize = 50000000;
httpsElement.MaxReceivedMessageSize = 50000000;
httpsElement.MaxBufferPoolSize = 50000000;
httpsElement.RequireClientCertificate = true;
// Others
httpsElement.UseDefaultWebProxy = true;
binding.Elements.Add(httpsElement);
return binding;
}
And Service Sertificate set as
client.ClientCredentials.ClientCertificate.Certificate=cert;// From pfx file
client.ClientCredentials.ServiceCertificate.DefaultCertificate =serverCert;//from server certificate
I try to sign with my company smart card which is ACS38 smart card. If I use DefaultAlgotihmSuite Basic128 or Basic128Rsa15 then smartCard certificate succesfully sign body elements. I change algorihmsuite Basic256Sha256Rsa15 for requirement then I get KeySet does not exist. In this Smart Card have private key but WCF does not reach that private key.
Is there way to sign to Sign Soap Body with Sha256Rsa on SmartCard ?

The 'Action', 'http://www.w3.org/2005/08/addressing' required message part was not signed

I am accessing an external java-based web service I have no control over from a WCF client, using dual certificates for encryption and signature as well as custom binding. I am getting a successful response from the server but WCF is throwing a MessageSecurityException : The 'Action', 'http://www.w3.org/2005/08/addressing' required message part was not signed.
My custom binding:
private CustomBinding GetCustomBinding()
{
CustomBinding binding = new CustomBinding();
binding.OpenTimeout = new TimeSpan(0, 0, 20);
binding.CloseTimeout = new TimeSpan(0, 0, 20);
binding.SendTimeout = new TimeSpan(0, 5, 0);
binding.ReceiveTimeout = new TimeSpan(0, 5, 0);
var userNameToken = new UserNameSecurityTokenParameters();
userNameToken.InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient;
var securityElement = new AsymmetricSecurityBindingElement();
securityElement.EnableUnsecuredResponse = true;
securityElement.IncludeTimestamp = true;
securityElement.RecipientTokenParameters = new X509SecurityTokenParameters(X509KeyIdentifierClauseType.IssuerSerial, SecurityTokenInclusionMode.Never);
securityElement.InitiatorTokenParameters = new X509SecurityTokenParameters(X509KeyIdentifierClauseType.IssuerSerial, SecurityTokenInclusionMode.AlwaysToRecipient);
securityElement.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Basic128Rsa15;
securityElement.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
securityElement.SetKeyDerivation(false);
securityElement.EndpointSupportingTokenParameters.Signed.Add(userNameToken);
securityElement.MessageProtectionOrder = System.ServiceModel.Security.MessageProtectionOrder.SignBeforeEncrypt;
securityElement.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
binding.Elements.Add(securityElement);
var encodingElement = new TextMessageEncodingBindingElement();
encodingElement.MessageVersion = MessageVersion.Soap11WSAddressing10;
encodingElement.WriteEncoding = Encoding.UTF8;
encodingElement.ReaderQuotas.MaxArrayLength = 50000000;
encodingElement.ReaderQuotas.MaxStringContentLength = 50000000;
binding.Elements.Add(encodingElement);
var httpsElement = new HttpsTransportBindingElement();
httpsElement.MaxBufferSize = 50000000;
httpsElement.MaxReceivedMessageSize = 50000000;
httpsElement.MaxBufferPoolSize = 50000000;
httpsElement.UseDefaultWebProxy = true;
binding.Elements.Add(httpsElement);
return binding;
}
Now I don't care if that Action element is signed or not, or even if it's not there at all, but hacking the response to remove the tag altogether results in a 'No signature message parts were specified for messages with the '' action.' exception.
How can I configure my client to accept the Action and other addressing elements in the response message as they are? Alternatively, what can I change them to so WCF will let them pass?
To override the default checking of the remote Secure Sockets Layer (SSL) certificate used for authentication, specify this on client:
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
To investigate the certificate errors, check the sslPolicyErrors parameter of the RemoteCertificateValidationCallback delegate (Link to MSDN manual page).

Increase MaxItemsInObjectGraph for WCF Service client

I am referencing a WCF service from a C# dll so the app.config file generated is not being read. I am manually trying to create a service client via the code below; however, I am getting errors that I need to increase the MaxItemsInObjectGraph. The service that is running is already set to int.MaxValue so I just need to increase it in the TestServiceClient now. Any ideas?? Thanks in advance!
var client = new TestServiceClient(GetBinding(), GetEndpointAddress());
private static EndpointAddress GetEndpointAddress()
{
var endpoint = new EndpointAddress("https://localhost:8000/ServiceModel/service");
return endpoint;
}
private static Binding GetBinding()
{
var basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport)
{
MessageEncoding = WSMessageEncoding.Text,
TextEncoding = Encoding.UTF8,
BypassProxyOnLocal = false,
UseDefaultWebProxy = true,
CloseTimeout = new TimeSpan(10, 0, 0),
OpenTimeout = new TimeSpan(10, 0, 0),
SendTimeout = new TimeSpan(10, 0, 0),
ReceiveTimeout = new TimeSpan(10, 0, 0),
HostNameComparisonMode = HostNameComparisonMode.StrongWildcard,
MaxBufferPoolSize = Int32.MaxValue,
MaxReceivedMessageSize = Int32.MaxValue,
AllowCookies = false,
TransferMode = TransferMode.StreamedResponse,
ReaderQuotas =
{
MaxDepth = 32,
MaxStringContentLength = Int32.MaxValue,
MaxArrayLength = 6553600,
MaxBytesPerRead = 4096,
MaxNameTableCharCount = 16384
}
};
return basicHttpBinding;
}
Below is my solution:
private static ITestServiceClient GetClient()
{
var factory = new ChannelFactory<ITestServiceClient >(GetBinding(), GetEndpointAddress());
foreach (var dataContractBehavior in factory.Endpoint.Contract.Operations
.Select(operation => operation.Behaviors.Find<DataContractSerializerOperationBehavior>())
.Where(dataContractBehavior => dataContractBehavior != null))
{
dataContractBehavior.MaxItemsInObjectGraph = Int32.MaxValue;
}
var client = factory.CreateChannel();
return client;
}
Try in client.Endpoint.Contract.Operations
foreach (var operation in operations)
{
var dataContractBehavior = operation.Behaviors.Find<DataContractSerializerOperationBehavior>();
if (dataContractBehavior != null)
{
dataContractBehavior.MaxItemsInObjectGraph = value;
}
}

Consuming a web service using digest authentication

We are using C# to send XML data via SOAP. The service requires HttpDigest authentication with #PasswordDigest and #Base64Binary Nonce. Our binding code:
protected BasicHttpBinding binding = new BasicHttpBinding()
{
Name = "ShipmentServiceSoapBinding",
CloseTimeout = new TimeSpan(0, 01, 0),
OpenTimeout = new TimeSpan(0, 01, 0),
ReceiveTimeout = new TimeSpan(0, 10, 0),
SendTimeout = new TimeSpan(0, 5, 0),
AllowCookies = false,
BypassProxyOnLocal = false,
HostNameComparisonMode = HostNameComparisonMode.StrongWildcard,
MaxBufferPoolSize = 5242880,
MaxReceivedMessageSize = 655360,
MessageEncoding = WSMessageEncoding.Text ,
TextEncoding = new UTF8Encoding(),
UseDefaultWebProxy = true,
ReaderQuotas = new XmlDictionaryReaderQuotas() { MaxDepth = 32, MaxStringContentLength = 81920, MaxArrayLength = 1638400, MaxBytesPerRead = 409600, MaxNameTableCharCount = 163840 },
Security = new BasicHttpSecurity() { Mode = BasicHttpSecurityMode.TransportWithMessageCredential,
//Message = new BasicHttpMessageSecurity() { AlgorithmSuite = SecurityAlgorithmSuite.Default, ClientCredentialType = BasicHttpMessageCredentialType.UserName},
Transport = new HttpTransportSecurity(){ ClientCredentialType = HttpClientCredentialType.Digest}},
};
We are encountering 3 different problems based on what type of BasicHttpSecurityMode we are choosing.
Transport - The XML does not include any security information
TransportCredentialOnly - The error we get states that the endpoint cannot be https://
TransportWithMessagecredential - This isn't using digest
Now their ServiceReference allows us to use ClientCredentials class, so here is how we tried using HttpDigest:
typeClient.ClientCredentials.HttpDigest.ClientCredential.UserName = "username";
typeClient.ClientCredentials.HttpDigest.ClientCredential.Password = "password";
I've read on other StackOverflow question that for digest we should be using SoapHeader with AuthHeader, but there is no way for us to match it with what they give is in the API. Is there any other way of doing it? Or is their API not written correctly for C#?
It is much more complicated to use digest auth in this scenario - you will need to implement IClientMessageInspector to get it working... this enables you to modify the http headers in a way that is needed for digest auth.
Helpful links:
https://stackoverflow.com/a/3257760/847363
http://benpowell.org/supporting-the-ws-i-basic-profile-password-digest-in-a-wcf-client-proxy/
http://social.msdn.microsoft.com/Forums/en/wcf/thread/0f09954e-3cef-45b3-a00d-f0f579a06bf7
http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iclientmessageinspector.aspx
http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iclientmessageinspector.beforesendrequest.aspx
http://yuzhangqi.itpub.net/post/37475/500654
http://wcfpro.wordpress.com/category/wcf-extensions/
http://social.technet.microsoft.com/wiki/contents/articles/1322.how-to-inspect-wcf-message-headers-using-iclientmessageinspector-en-us.aspx
http://weblogs.asp.net/paolopia/archive/2007/08/23/writing-a-wcf-message-inspector.aspx
http://wcfpro.wordpress.com/2011/03/29/iclientmessageinspector/

Categories