WCF custom message security - c#

I need to use polling technique to notify clients about changes in server-side. So I tried to use DuplexHttpBinding (http://code.msdn.microsoft.com/duplexhttp). I works fine with non-secured messages, but I need to use message-level security in my project (UsernameForCertificate). Ok, I decided to add SymmetricSecurityBindingElement to binding collection:
var securityElement = SecurityBindingElement.CreateUserNameForCertificateBindingElement();
collection.Add(securityElement);
And then problem happened. If we use message-level security all messages include security-headers with message signature, like this:
<o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:s="http://www.w3.org/2003/05/soap-envelope">
....
</o:Security>
And custom polling messages which are send by custom request channel has no security headers, so exception occurs while sending this message through the channel with message-level security:
System.ServiceModel.Security.MessageSecurityException, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
No signature message parts were specified for messages with the 'http://samples.microsoft.com/duplexhttp/pollingAction' action.
Please, advice workaround how to add proper security headers to my custom polling messages before sending them inside custom request channel. You can download source code by the link posted before and simply try to use it with UsernameForCertificate security to reproduce the issue.
Thank you.

After couple of days & deep investigation I found the solution. It seems that we should modify ChannelProtectionRequirements when creation custom Channel Facroty & Channel Listener to add encryption & signature parts to our custom messages. Here is the sample:
private static void ApplyChannelProtectionRequirements(BindingContext context)
{
var cpr = context.BindingParameters.Find<ChannelProtectionRequirements>();
if (cpr != null)
{
XmlQualifiedName qName = new XmlQualifiedName("customHeader", "namespace");
MessagePartSpecification part = new MessagePartSpecification(qName);
cpr.IncomingEncryptionParts.AddParts(part, "incomingAction");
cpr.IncomingSignatureParts.AddParts(part, "incomingAction");
cpr.OutgoingEncryptionParts.AddParts(part, "outgoingAction");
cpr.OutgoingSignatureParts.AddParts(part, "outgoingAction");
}
}

Related

Programmatically implement WCF with Certificate

I am quite new to WCF and trying to get my head around the security. I am still reading and learning, but I came to a point where I got a working version of WCF with Certificate authentication. I know that the code has some weaknesses; however, my initial goal was to create communication using certificate authentication. Also, I wanted to create everything programmatically (no Web.config configurations for the services or clients). The reason for this is that the client should be able to link an Assembly (Class Library) and get access to the server. Also, I am loading the certificates from the file system (again, I know this is not secure). I would like to get a little bit feedback.
The following client snippet is creating an object that I can use to connect to the server. The anonymous type T is my service interface e.g. IService.
Here is my client implementation:
var url = "URL TO WS";
var binding = new WSHttpBinding
{
Security =
{
Mode = SecurityMode.Message,
Message = {ClientCredentialType = MessageCredentialType.Certificate}
}
};
var endpoint = new EndpointAddress(url);
var channelFactory = new ChannelFactory<T>(binding, endpoint);
if (channelFactory.Credentials != null)
{
channelFactory.Credentials.ClientCertificate.Certificate =
new X509Certificate2(#"PATH\TO\Client.pfx"); // Client Certificate PRIVATE & PUBLIC Key
channelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None; // I know this is not good, but I dont have a valid certificate from a trusted entity
}
wcfClient = channelFactory.CreateChannel();
return wcfClient;
The service is a bit more complex. I use .svc files with their code-behind. If I understand the use of .svc files correctly, then I believe this is the entry point where the .NET framework creates a ServiceHost and automatically opens it? In my implementation I do not open the ServiceHost, I only implemented a ServiceHostFactoryBase and referenced it in the .svc Markup language. Look at the Factory section - this is the part where I implement my custom Host Factory.
<%# ServiceHost Language="C#" Debug="true"
Service="Service.Services.LevelService" CodeBehind="LevelService.svc.cs"
Factory="Service.Security.ServiceHostFactory.HostFactory" %>
And my custom Host Factory looks like this:
public class HostFactory : ServiceHostFactoryBase
{
public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
{
var serviceType = Type.GetType(constructorString);
if (serviceType.GetInterfaces().Count() != 1)
throw new NotImplementedException("The service can only have one implemented interface");
var interfaceType = serviceType.GetInterfaces()[0];
var myServiceHost = new ServiceHost(serviceType, baseAddresses);
var httpBinding = new WSHttpBinding();
httpBinding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
httpBinding.Security.Mode = SecurityMode.Message;
myServiceHost.Credentials.ServiceCertificate.Certificate = new X509Certificate2(#"PATH\TO\Server.pfx");
myServiceHost.Credentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom;
myServiceHost.Credentials.ClientCertificate.Authentication.CustomCertificateValidator = new MyX509CertificateValidator();
myServiceHost.Credentials.ClientCertificate.Certificate = new X509Certificate2(#"PATH\TO\Client.cer");
myServiceHost.AddServiceEndpoint(interfaceType, httpBinding, String.Empty);
return myServiceHost;
}
}
The custom validator doess't do much yet, but here it is as well:
public class MyX509CertificateValidator : X509CertificateValidator
{
public override void Validate(X509Certificate2 certificate)
{
// Check that there is a certificate.
if (certificate == null)
{
throw new ArgumentNullException("certificate");
}
// Check that the certificate issuer matches the configured issuer.
//throw new SecurityTokenValidationException("Certificate was not issued by a trusted issuer");
}
}
If I understand correctly, the Server has ONLY the PUBLIC key of the client registered since I only reference the .cer file.
My big question is now, if I would like to get anything like this on a production server - and lets assume nobody will actually get the executables (including the certificates), would this be a possible solution to keep unwanted people out of my webservice? Basically, I don't want anybody else consuming my webservice - only if you have the proper certificate. Also, how much of an issue is the part where I set on the client:
CertificateValidationMode = X509CertificateValidationMode.None
I know there are many questions - but overall, I would like to know if I made some fundamental mistakes in this implementation.
Ok,
after going through a lot of tutorials and demo applications, I figured out that the best way to go ahead is actually using the Certificate Store on Windows. However, I still might consider a hybrid solution where the Server has the certificates in the Certificate store and the client has it embedded in a resource. If you are struggling with WCF and Certificates, have a look at those links:
IIS7 Permissions Overview - ApplicationPoolIdentity
I was able to create Transport as well as Message secured WCF web services. I would suggest to READ the linked articles because there is so much information that will make you understand certificates and their usage. Especially when dealing with self-singed certificates!
I ended up implementing wsHttpBinding using Message Security Mode + Client Certificate with ChainTrust.
Hope this will help someone else!

Connecting to IBM MQ over SSL via .net client

I am trying to connect to a MQ server queue via a .NET client. I need to use the certificate for secured communication. Here is the code that I have:
MQEnvironment.SSLKeyRepository = "*SYSTEM";
MQEnvironment.ConnectionName = connectionName;
MQEnvironment.Channel = channelName;
MQEnvironment.properties.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);
MQEnvironment.SSLCipherSpec = "TLS_RSA_WITH_AES_256_CBC_SHA";
queueManager = new MQQueueManager(queueManagerName, channelName, connectionName);
queue = queueManager.AccessQueue(SendQueueName,MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING);
queueMessage = new MQMessage();
queueMessage.WriteString(message);
queueMessage.Format = MQC.MQFMT_STRING;
queue.Put(queueMessage, new MQPutMessageOptions());
Every time I try to put the message on the queue, I get this error message
Reason Code: 2059
MQexp.Message: MQRC_Q_MGR_NOT_AVAILABLE
I have checked my variables for the queue manager name, queue name etc and they are correct.
I was also able to connect to a different queue without SSL, I believe that my code is not furnishing enough information to establish a successful connection.
Any help on this would be appreciated.
Thanks,
Kunal
I had the same problem and error message. After enabling tracing I was able to isolate the problem.
I always wondered, how the client is selecting the correct client certificate from the store. The trace output revealed following:
000001B2 15:53:46.828145 20776.10 Created an instance of SSLStreams
000001B3 15:53:46.828145 20776.10 Setting current certificate store as 'Computer'
000001B4 15:53:46.828145 20776.10 Created store object to access certificates
000001B5 15:53:46.834145 20776.10 Opened store
000001B6 15:53:46.834145 20776.10 Accessing certificate - ibmwebspheremqmyusername
000001B7 15:53:46.835145 20776.10 TLS12 supported - True
000001B8 15:53:46.837145 20776.10 Setting SslProtol as Tls
000001B9 15:53:46.837145 20776.10 Starting SSL Authentication
In my case, I had to set the friendly name of the client certificate to ibmwebspheremqmyusername (replace "myusername" with your userid) and set the label in the code aswell:
properties.Add(MQC.MQCA_CERT_LABEL, "ibmwebspheremqmyusername");
To enable tracing, add following to your app.config/web.config where the path points to a location that contains a file named mqtrace.config:
<appSettings>
<add key="MQTRACECONFIGFILEPATH" value="C:\MQTRACECONFIG" />
</appSettings>
Sample content of mqtrace.config (specified directories must exist in advance):
<?xml version="1.0" encoding="utf-8"?>
<traceSettings>
<MQTRACELEVEL>2</MQTRACELEVEL>
<MQTRACEPATH>C:\MQTRACEPATH</MQTRACEPATH>
<MQERRORPATH>C:\MQERRORLOGPATH</MQERRORPATH>
</traceSettings>
Here are some links for more detail:
Tracing:
https://www.ibm.com/support/knowledgecenter/SSFKSJ_8.0.0/com.ibm.mq.dev.doc/q123550_.htm
Why label:
http://www-01.ibm.com/support/docview.wss?uid=swg21245474

Onvif SOAP request with SOAP level authentication and HTTP authentication

This question has been discussed in several topics here but I could not find the answer for me.
What I'm trying to do is use an IP camera through the Onvif interface. I've generated the web services from the WSDL files available in the Onvif homepage, and added the custom SOAP authentication code as suggested here, and I am able to retrieve the device capabilities etc. etc.
But for some services, e.g, PTZ control, also HTTP authentication is needed. My code removes the ClientCredentials behaivor (so yeah, I guess setting them does not make any sense, but I still left those lines in hope that maybe the HTTP transport would try to use them):
HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement();
httpBindingElement.AuthenticationScheme = AuthenticationSchemes.Basic;
...
PTZClient ptzClient = new PTZClient(customBinding, endPointAddress);
ptzClient.Endpoint.Behaviors.Remove(typeof(System.ServiceModel.Description.ClientCredentials));
UsernameClientCredentials onvifCredentials = new UsernameClientCredentials(new UsernameInfo(_username, _password));
ptzClient.Endpoint.Behaviors.Add(onvifCredentials);
ptzClient.ClientCredentials.UserName.UserName = _username;
ptzClient.ClientCredentials.UserName.Password = _password;
Still when I look at wireshark, i see that the SOAP authentication is generated but no HTTP authentication header is set (well, I already expected that since i have a custom behaivor here). So the question is, if I am creating the binding this way, what are my best options to add HTTP authentication headers? Can I just add a message inspector, and if so, any examples? Must I create a different transport binding? I've seen people advising others to use BasicHttpBinding and then setting the Security property on that, but where do the credentials go in that case and how do I apply the BasicHttpBinding instance to my binding? Are there any callbacks in the WCF that get triggered by the HTTP 401 code that i can hook up to and then provide the header? This is actually my first experience with WCF and so far I've done everything from examples found in the internet, but as for this particular issue I haven't been able to find anything.
If anyone is interested this is how I got it working. I combined the BasicHttpBinding with the client credentials in a following way:
TransportSecurityBindingElement transportSecurity = new TransportSecurityBindingElement();
// UsernameCredentials is a class implementing WS-UsernameToken authentication
transportSecurity.EndpointSupportingTokenParameters.SignedEncrypted.Add(new UsernameTokenParameters());
transportSecurity.AllowInsecureTransport = true;
transportSecurity.IncludeTimestamp = false;
TextMessageEncodingBindingElement messageEncoding = new TextMessageEncodingBindingElement(MessageVersion.Soap12, Encoding.UTF8);
HttpClientCredentialType[] credentialTypes = new HttpClientCredentialType[3] { HttpClientCredentialType.None, HttpClientCredentialType.Basic, HttpClientCredentialType.Digest };
...
foreach (HttpClientCredentialType credentialType in credentialTypes)
{
BasicHttpBinding httpBinding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
httpBinding.Security.Transport.ClientCredentialType = credentialType;
BindingElementCollection elements = new BindingElementCollection(new BindingElement[1]{messageEncoding});
foreach(BindingElement element in httpBinding.CreateBindingElements())
{
if (element is TextMessageEncodingBindingElement)
continue;
elements.Add(element);
}
CustomBinding customBinding = new CustomBinding(elements);
DeviceClient deviceClient = new DeviceClient(customBinding, endPointAddress);
if (credentialType == HttpClientCredentialType.Basic)
{
// Set all credentials, not sure from which one WCF actually takes the value
deviceClient.ClientCredentials.UserName.UserName = pair[0];
deviceClient.ClientCredentials.UserName.Password = pair[1];
}
else if (credentialType == HttpClientCredentialType.Digest)
{
deviceClient.ClientCredentials.HttpDigest.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation;
deviceClient.ClientCredentials.HttpDigest.ClientCredential.UserName = pair[0];
deviceClient.ClientCredentials.HttpDigest.ClientCredential.Password = pair[1];
}
}
This works efficiently with a device for which we do not know the authentication mode and works on both (HTTP/SOAP) authentication level.
I detailed how HTTP digest works in another answer.
Remember that only functions of class PRE_AUTH, according to ยง5.12.1 of the Core spec, require authentication.
You should invoke a function of any class but PRE_AUTH without any form authentication. If you get a HTTP 401 then you have to use HTTP digset, otherwise you'll have to got with WS-UsernameToken.
You can't directly use HTTP digest because you'll need at least the device to send you the challange for HTTP digest.

C#: What is the best method to send support request via email?

I have a windows forms application that I am adding a request support form to, and would like the user to be able to input the values and hit a button. Once the button is pushed I can either:
Open a new mail message and auto populate the message. (Not sure how to do this)
Submit the request via a http form on my website. (I know how to do this)
Send an email directly from the code of the application. (I know how to do this)
What I want to know is what would be the best method to use? I think option 1 is the most transparent, and the user will see exactly what is being sent, but I am not sure how to ensure it works no matter what email client they use.
I see there being potential issues with option two, specifically a firewall possibly stopping the submission. But option 2 would allow me to supply them with a ticket number right then and there for their request.
Thanks for the help.
For Option 1, as suggested, use the mailto handler.
Format your string like so: string.Format("mailto:support#example.com?subject={0}&body={1}", subject, body). Don't forget to UrlEncode the subject and body values.
Then use System.Diagnostics.Process.Start() with your string.
This will launch the registered mail handler (Outlook, Windows Live Mail, Thunderbird, etc) on the system.
For option 1 : If the message body is short, then invoking the mailto handler from inside your code no longer requires that they be using outlook. It's kinda a cheap hack, but it's completely cross-platform for local mail clients. (If they're using something like gmail, you're still SOL, though)
Option 2) is the best to avoid enterprise firewall issues because the HTTP port may not be blocked.
Option 2) is the best for simple configuration. The only config key you will have is the service/page url. Then your SMTP configuration will stay on your webserver.
Now you will have to choose between using a webpage (if one already exists) or a webservice (which is best fitted for your feature).
For option (1) be prepared to deal with Outlook version problems. But this is not hard (again if we are talking about Outlook, last version)
//using Microsoft.Office.Interop.Outlook;
private void OutlookMail(string Subject, string Body)
{
ApplicationClass app = new ApplicationClass();
NameSpaceClass ns = (NameSpaceClass)app.GetNamespace("mapi");
ns.Logon("", "", true, true);
MailItem mi =
(MailItem)app.CreateItem(OlItemType.olMailItem);
mi.Subject = Subject;
int EOFPos = Body.IndexOf(char.Parse("\0"));
if (EOFPos != -1)
{
log.Error("EOF found in Mail body");
ErrorDialog ed = new ErrorDialog(TietoEnator.Common.ErrorDialog.ErrorDialog.Style.OK, "Export Error", "File could not be exported correctly, please inform responsible person", "", "EOF char detected in the body of email message.");
ed.ShowDialog();
Body=Body.Replace("\0", "");
}
mi.HTMLBody = "<html><head><META content='text/html; charset=CP1257' http-equiv=Content-Type></head><body><table>"+Body+"</table></body></html>";
mi.BodyFormat = OlBodyFormat.olFormatHTML;//.olFormatPlain;
mi.Display(0); // show it non - modally
ns.Logoff();
}
BTW for automatic support requests I plan to use in my current project "Microsoft Enterprise Logging Support Block" email sending functionality.

How to Domainkeys/DKIM email signing using the C# SMTP client?

I have written an program in C# which sends out emails. Now I have a requirement to sign outbound emails using Dominkeys/DKIM, but I'm not sure how to do it.
I have set up all keys, but I don't know how to get those and how to include them in the email header.
There is a fundamental problem with trying to do DKIM signatures with System.Net.Mail.MailMessage and System.Net.Mail.SmtpClient which is that in order to sign the message, you need to poke the internals of SmtpClient in order to hash the message body as one of the steps in generating the DKIM-Signature header. The problem comes in when you have alternative views or attachments because SmtpClient will generate new multipart boundaries each time it writes out the message which breaks the body hash and thus the DKIM-Signature validity.
To work around this, you can use the MimeKit and MailKit open source libraries for .NET as an alternative framework to using System.Net.Mail.
To add a DKIM signature to a message in MimeKit, you would do something like this:
MimeMessage message = MimeMessage.CreateFromMailMessage(mailMessage);
HeaderId[] headersToSign = new HeaderId[] { HeaderId.From, HeaderId.Subject, HeaderId.Date };
string domain = "example.net";
string selector = "brisbane";
DkimSigner signer = new DkimSigner ("C:\my-dkim-key.pem", domain, selector)
{
SignatureAlgorithm = DkimSignatureAlgorithm.RsaSha1,
AgentOrUserIdentifier = "#eng.example.com",
QueryMethod = "dns/txt",
};
// Prepare the message body to be sent over a 7bit transport (such as
// older versions of SMTP). This is VERY important because the message
// cannot be modified once we DKIM-sign our message!
//
// Note: If the SMTP server you will be sending the message over
// supports the 8BITMIME extension, then you can use
// `EncodingConstraint.EightBit` instead.
message.Prepare (EncodingConstraint.SevenBit);
message.Sign (signer, headersToSign,
DkimCanonicalizationAlgorithm.Relaxed,
DkimCanonicalizationAlgorithm.Simple);
To send the message using MailKit, you would do something like this:
using (var client = new MailKit.Net.Smtp.SmtpClient ()) {
client.Connect ("smtp.gmail.com", 465, true);
client.Authenticate ("username", "password");
client.Send (message);
client.Disconnect (true);
}
Hope that helps.
see https://github.com/dmcgiv/DKIM.Net it's a DomainKeys Identified Mail (DKIM) implementation for .Net written in C# - it enables you to sign MailMessage objects.
Use
http://www.mimekit.org
Not only does it allow to use DKIM for signing, also you can include S/MIME certificates, PGP certificates and more.
Also, its a very mature lib - the only one i've found that handles foreign languages (apart from english) correctly, since its completely and thoroughly coded with unicode in mind.
Its free and opensource.
This solved it for me when using Mailenable as SMTP relay server.
http://www.mailenable.com/kb/content/article.asp?ID=ME020700
When creating the DKIM TXT record on the domain name don't forget to use the active selector as prefix => yourselector._domainkey.yourdomainname.be
If you are looking to DKIM-sign the body of the MailMessage then DKIM.NET is great. If you are looking to have alternative views in your message then I wasnt able to find a solution and wrote my own (open-source with the usual disclaimers) that can be found at https://github.com/yannispsarras/DKIM-AlternativeViews
I understand this is a pretty old thread but I thought it may help someone.
i didnt find much help on this issue, but my problem got solve by configuring smtp server.
i cant post those steps as i am using 3rd party smtp server and every server has their own configuration. after proper configuration my smtp automatically adds DM/DKIM signature.

Categories