How to associate a certificate with a soap request in C#? - c#

I am new to Web Services in general, and we are using .Net Framework 4.5.2, anyway I am trying to consume a web service that requires a certificate and a password.
I added the certificate gained from the providers in the project properties --> Resources --> file --> add, I also tried to use the SetCertificate() function but It seems to be a little complicated for me so I stick with loading the certificate from the properties as mentioned, however I already set all the binding setting as wanted, but somehow I am missing something, Here is my code:
string clientUrl = "some wsdl URL goes here";
BasicHttpsBinding binding = new BasicHttpsBinding
{
MaxReceivedMessageSize = Int32.MaxValue,
MaxBufferSize = Int32.MaxValue,
SendTimeout = new TimeSpan(0, 15, 0),
MessageEncoding = WSMessageEncoding.Text,
Security = {
Mode = BasicHttpsSecurityMode.Transport,
Transport = {
ClientCredentialType = HttpClientCredentialType.Certificate
}
}
};
ClientsClient testClient = new ClientsClient(binding, new EndpointAddress(new Uri(clientUrl)));
testClient.ClientCredentials.ClientCertificate.Certificate = LoadCertification();
private X509Certificate2 LoadCertification()
{
byte[] bytes = Properties.Resources.publicCert;
return new X509Certificate2(bytes, "password");
}
Note 1: The certificate extenstion is '.p12', It may be a list of certifications, if that is the case!, is it possible to pass them all?.
In the code I presented I am always getting The exception:
System.ServiceModel.ProtocolException: The 'Security' header from the namespace 'Some Http url goes here' not was understood by the recipient of the message. The message was not processed. The error usually indicates that the sender of the message has enabled a communication protocol that cannot be processed by the recipient. Verify that the client binding configuration is consistent with the service binding.
I tried to test the web service with "SOAP UI" and it worked, which made me sure that I am doing something wrong with the code, So I appreaciate any possible help that explains how to associate the certifcate in the code in the right way!.
EDIT:
in the .p12 file there are 3 certifications, which I tried to add also like this:
X509Certificate2Collection coll = LoadCertification();
int count = 0;
foreach (X509Certificate2 cert in coll)
{
testClient.ClientCredentials.ClientCertificate.Certificate = cert;
count++;// this variable is just to check the number of certificates
}
And I modified the loadCertification() method to look like this:
private X509Certificate2Collection LoadCertification()
{ string certPath = "C:/Users/ISA/Desktop/Progetti/Certificato e password/name.p12";
X509Certificate2Collection coll = new X509Certificate2Collection();
coll.Import(certPath , "password", X509KeyStorageFlags.DefaultKeySet);
return coll;
}

Related

gRPC and ASP Net Core: using SslCredentials with non-null arguments is not supported by GrpcChannel

I am trying to connect from a client to the service. The service is configurated to use a self signed Ssl certificate and I am trying to configurate the client with the client certificate. I am using this code:
string cacert = System.IO.File.ReadAllText("certificados/ca.crt");
string cert = System.IO.File.ReadAllText("certificados/client.crt");
string key = System.IO.File.ReadAllText("certificados/client.key");
KeyCertificatePair keypair = new KeyCertificatePair(cert, key);
SslCredentials sslCreds = new SslCredentials(cacert, keypair);
var channel = GrpcChannel.ForAddress("https://x.x.x.x:5001", new GrpcChannelOptions { Credentials = sslCreds });
var client = new Gestor.GestorClient(channel);
But I am getting the following error: using SslCredentials with non-null arguments is not supported by GrpcChannel.
I don't understand very good the message error. SslCredentials is ChannelCredentials? type, and SslCreds is Grpc.Core.SslCredentials. It can be compiled, so the type I guess it is correct.
What I would like to know it is how I can configure the client to use the self signed certificate that I have created.
Thanks.
The SslCredentials support in only available grpc-dotnet is to provide some level of compatibility with Grpc.Core in the most common use case, it doesn't expose all the functionality though. In grpc-dotnet, only SslCredentials() (parameterless which uses the default roots) is supported. If you want to provide your self-signed creds, you can certainly do that, you'll need to use a different API for configuring GrpcChannel:
See example here (creating a GrpcChannel with custom credentials).
https://github.com/grpc/grpc-dotnet/blob/dd72d6a38ab2984fd224aa8ed53686dc0153b9da/testassets/InteropTestsClient/InteropClient.cs#L170
I spend a fair bit of time googling around for solutions to this problem, and didn't find a concise answer. Here is ultimately how I was able to configure a dotnet client to use mutual SSL authentication:
MyService.MyServiceClient GetClient(){
var httpClientHandler = new HttpClientHandler();
// Validate the server certificate with the root CA
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, _) => {
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
chain.ChainPolicy.CustomTrustStore.Add(new X509Certificate2("ca.crt"));
return chain.Build(cert);
};
// Pass the client certificate so the server can authenticate the client
var clientCert = X509Certificate2.CreateFromPemFile("client.crt", "client.key");
httpClientHandler.ClientCertificates.Add(clientCert);
// Create a GRPC Channel
var httpClient = new HttpClient(httpClientHandler);
var channel = GrpcChannel.ForAddress("https://localhost:8080", new GrpcChannelOptions{
HttpClient = httpClient,
});
return new MyService.MyServiceClient(channel);
}

How do I disable validation of the x509 certificate used to validate a message signature?

I have a client that calls an API that signs its response messages. The signature validation setup requires special binding that looks like this:
public class SignatureBinding : Binding
{
public override BindingElementCollection CreateBindingElements()
{
var signingElement = new AsymmetricSecurityBindingElement
{
AllowInsecureTransport = false,
RecipientTokenParameters = new X509SecurityTokenParameters(X509KeyIdentifierClauseType.IssuerSerial, SecurityTokenInclusionMode.Never),
InitiatorTokenParameters = new X509SecurityTokenParameters(X509KeyIdentifierClauseType.IssuerSerial, SecurityTokenInclusionMode.AlwaysToRecipient),
DefaultAlgorithmSuite = SecurityAlgorithmSuite.Basic256,
SecurityHeaderLayout = SecurityHeaderLayout.Strict,
MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt,
MessageSecurityVersion = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10,
AllowSerializedSigningTokenOnReply = true
};
signingElement.SetKeyDerivation(false);
return new BindingElementCollection
{
signingElement,
new HttpsTransportBindingElement()
};
}
}
And in the ClientCredentials behavior:
public class CredentialsBehavior : ClientCredentials
{
public CredentialsBehavior()
{
base.ServiceCertificate.DefaultCertificate = store.FindBySerialNumber(signatureCertSN);
}
//Code omitted
}
I have confirmed that the above code works fine when run from an ordinary computer. The message is sent, the server crafts a response and signs it, it comes back, the client validates the signature, and all is well.
However, there is a failure when running from the intended server, which cannot access CRL services due to firewalls. The ServiceModel call returns an error when I send the message over the channel. The error pertains to the certificate that contains the public key for validating the signature. The error is:
The X.509 certificate CN=somecert.somedomain.com, OU=CE_Operations, O="MyCompany, Inc.", L=City, S=State, C=US chain building failed. The certificate that was used has a trust chain that cannot be verified. Replace the certificate or change the certificateValidationMode. The revocation function was unable to check revocation because the revocation server was offline.
The server exists in a domain that can't access CRLs so I disabled the check with help from this answer:
ServicePointManager.ServerCertificateValidationCallback += ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
ServicePointManager.CheckCertificateRevocationList = false;
However, the error persists. I'm guessing that ServerCertificateValidationCallback only fires for server certificates, and this certificate is different.
How do I convince the service model to allow the use of this certificate without checking the CRL or performing other validation procedures?
Set certificateValidationMode to None to ignore certificate validation X509CertificateValidationMode
This is a behavior, so if you want to do it programmatically you should bind it as new behavior to your service :
ServiceHost host = new ServiceHost(typeof(Service));
ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "http://...");
var endpointClientbehavior = new ClientCredentials();
endpointClientbehavior.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
endpoint.Behaviors.Add(endpointClientbehavior);

DocuSign: Error calling CreateEnvelope

I have the following code for adding a new Envelope with a local file:
EnvelopeDefinition envelope = new EnvelopeDefinition
{
Status = "sent"
};
// Get the contract file
Byte[] bytes = File.ReadAllBytes("[Local Filename]");
// Add a document to the envelope
DocuSign.eSign.Model.Document doc = new DocuSign.eSign.Model.Document();
doc.DocumentBase64 = System.Convert.ToBase64String(bytes);
doc.Name = contract.FileName;
doc.DocumentId = "1";
envelope.Documents = new List<DocuSign.eSign.Model.Document>();
envelope.Documents.Add(doc);
// Add a recipient to sign the documeent
Signer signer = new Signer();
signer.Email = recipientEmail;
signer.Name = recipientName;
signer.RecipientId = "1";
// Create a |SignHere| tab somewhere on the document for the recipient to sign
signer.Tabs = new Tabs();
signer.Tabs.SignHereTabs = new List<SignHere>();
SignHere signHere = new SignHere();
signHere.DocumentId = "1";
signHere.PageNumber = "1";
signHere.RecipientId = "1";
signHere.XPosition = "100";
signHere.YPosition = "150";
signer.Tabs.SignHereTabs.Add(signHere);
envelope.Recipients = new Recipients();
envelope.Recipients.Signers = new List<Signer>();
envelope.Recipients.Signers.Add(signer);
DocuSignAuthentication Creds = new DocuSignAuthentication
{
Username = "[My Username]",
Password = "[My Password]",
IntegratorKey = "[My Integration Key]"
};
ApiClient apiClient = new ApiClient("https://demo.docusign.net/restapi/v2/accounts/XXXXXXX");
string authHeader = JsonConvert.SerializeObject(Creds);
DocuSign.eSign.Client.Configuration cfg = new DocuSign.eSign.Client.Configuration(apiClient);
cfg.AddDefaultHeader("X-DocuSign-Authentication", authHeader);
EnvelopesApi envelopeApi = new EnvelopesApi(cfg);
EnvelopeSummary response = envelopeApi.CreateEnvelope("XXXXXXX", envelope);
The server returns a very little information in the error:
[ApiException: Error calling CreateEnvelope: ]
DocuSign.eSign.Api.EnvelopesApi.CreateEnvelopeWithHttpInfo(String accountId, EnvelopeDefinition envelopeDefinition, CreateEnvelopeOptions options) in
Y:\dev\SDKs\csharp\sdk\src\main\csharp\DocuSign\eSign\Api\EnvelopesApi.cs:2606
DocuSign.eSign.Api.EnvelopesApi.CreateEnvelope(String accountId, EnvelopeDefinition envelopeDefinition, CreateEnvelopeOptions options) in Y:\dev\SDKs\csharp\sdk\src\main\csharp\DocuSign\eSign\Api\EnvelopesApi.cs:2532
[Rest of the stack trace relates to our code]
If we try to use fiddler to capture any error messages from the server, the error becomes:
Could not establish trust relationship for the SSL/TLS secure channel
Is there anyway to get a more information about what's wrong with our request? Or is there an un-encrypted developer endpoint available to work through these kinds of issues? Any help you can spare would be greatly appreciated.
The error "Could not establish trust relationship for the SSL/TLS secure channel" means that the HTTPRequest call from the client (which can be your server, but is a client in the sense that it made the HTTPRequest) to the server (DocuSign in this case) could not use TLS over SSL (https:// address) to ensure that there's a certificate that allows to encrypt the information in the HTTPRequest and HttpResponse. This can happen for a variety of reasons including not having the current version of TLS on the client as well as having the wrong certificate or other issues with the network. I would recommend trying to make this call from a different server, potentially outside your corporate network to isolate the problem. Also, check the version of TLS to ensure it's at least 1.1

Onvif authentication with axis camara P1344 c#

I'm completely stuck with ONVIF authentication. I think I've tried everything or at least almost everything and I don't find enough information on the Internet. I have created the stub client using svcutil, my code to do the authentication is (one of them because I have tried a lot of things):
string uri = "http://140.0.22.39/onvif/services";
EndpointAddress serviceAddressPrueba = new EndpointAddress(uri);
HttpTransportBindingElement httpBinding = new HttpTransportBindingElement();
httpBinding.AuthenticationScheme = AuthenticationSchemes.Digest;
var messegeElement = new TextMessageEncodingBindingElement();
messegeElement.MessageVersion = MessageVersion.CreateVersion(EnvelopeVersion.Soap12, AddressingVersion.None);
CustomBinding bindprueba = new CustomBinding(messegeElement, httpBinding);
DeviceClient clientprueba = new DeviceClient(bindprueba, serviceAddressPrueba);
string passwordDigestBase64;
//HERE I PUT THE CODE TO ENCRYPT THE PASSWORD.
PasswordDigestBehavior behavior1 = new PasswordDigestBehavior("root",passwordDigestBase64);
clientprueba.Endpoint.Behaviors.Add(behavior1);
string d1;
string d2;
string d3;
string d4;
clientprueba.GetDeviceInformation(out d1, out d2, out d3, out d4);
After this there is the following error:
{"The remote server returned an unexpected response: (400) Bad Request."}
I will be very, very grateful if you please could help me with any information to solve this.
Try this way:
ServicePointManager.Expect100Continue = false;
var endPointAddress = new EndpointAddress("http://" + cameraAddress + "/onvif/device_service");
var httpTransportBinding = new HttpTransportBindingElement { AuthenticationScheme = AuthenticationSchemes.Digest };
var textMessageEncodingBinding = new TextMessageEncodingBindingElement { MessageVersion = MessageVersion.CreateVersion(EnvelopeVersion.Soap12, AddressingVersion.None) };
var customBinding = new CustomBinding(textMessageEncodingBinding, httpTransportBinding);
var passwordDigestBehavior = new PasswordDigestBehavior(adminName, adminPassword);
var deviceClient = new DeviceClient(customBinding, endPointAddress);
deviceClient.Endpoint.Behaviors.Add(passwordDigestBehavior);
Notice that it is important to set ServicePointManager.Expect100Continue to false.
A couple of things could cause this:
You've set a root password via web browser, thus locking the ONVIF user. Log in to the camera and add an ONVIF user (There's a special page for that)
Your password digest includes only the password, where it should include a concatenation of a random nonce, the creation time, and the password.
Your local clock is not synchronized with the camera's clock. call getSystemDateAndTime to read the remote clock and record the time differences between you.
These were the 3 out of the 4 major things that slowed me down (the 4th one was importing the wsdl, but it looks like you got it already)

MessageSecurityException: The security header element 'Timestamp' with the '' id must be signed

I'm asking the same question here that I've already asked on msdn forums http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/70f40a4c-8399-4629-9bfc-146524334daf
I'm consuming a (most likely Java based) Web Service with I have absolutely no access to modify. It won't be modified even though I would ask them (it's a nation wide system).
I've written the client with WCF. Here's some code:
CustomBinding binding = new CustomBinding();
AsymmetricSecurityBindingElement element = SecurityBindingElement.CreateMutualCertificateDuplexBindingElement(MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10);
element.AllowSerializedSigningTokenOnReply = true;
element.SetKeyDerivation(false);
element.IncludeTimestamp = true;
element.KeyEntropyMode = SecurityKeyEntropyMode.ClientEntropy;
element.MessageProtectionOrder = System.ServiceModel.Security.MessageProtectionOrder.SignBeforeEncrypt;
element.LocalClientSettings.IdentityVerifier = new CustomIdentityVerifier();
element.SecurityHeaderLayout = SecurityHeaderLayout.Lax;
element.IncludeTimestamp = false;
binding.Elements.Add(element);
binding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8));
binding.Elements.Add(new HttpsTransportBindingElement());
EndpointAddress address = new EndpointAddress(new Uri("url"));
ChannelFactory<MyPortTypeChannel> factory = new ChannelFactory<MyPortTypeChannel>(binding, address);
ClientCredentials credentials = factory.Endpoint.Behaviors.Find<ClientCredentials>();
credentials.ClientCertificate.Certificate = myClientCert;
credentials.ServiceCertificate.DefaultCertificate = myServiceCert;
credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
service = factory.CreateChannel();
After this every request done to the service fails in client side (I can confirm my request is accepted by the service and a sane response is being returned)
I always get the following exception
MessageSecurityException: The security
header element 'Timestamp' with the ''
id must be signed.
By looking at trace I can see that in the response there really is a timestamp element, but in the security section there is only a signature for body.
Can I somehow make WCF to ingore the fact Timestamp isn't signed?
You could try using a WCF Message contract. When you have a Message contract you can specify that the items in the header should be signed:
[MessageContract]
public class CustomType
{
[MessageHeader(ProtectionLevel = ProtectionLevel.Sign)]
string name;
[MessageHeader(ProtectionLevel = ProtectionLevel.EncryptAndSign)]
string secret;
I got this sorted out, the answer can be found in here:
http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/371184de-5c05-4c70-8899-13536d8f5d16
Main points: add a custom StrippingChannel to the custombinding to strip off the timestamp from the securityheader and configure WCF to not detect replies.

Categories