Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts

Tuesday, June 14, 2011

Test drive the shiny new Wcf interop bindings

@YaronNaveh

wcf.codeplex.com is the place where most of the wcf action happens at these days. If you have been following it recently you have seen a lot of activity around Rest and Http. As of yesterday Soap officially joins the codepex party. Microsoft has just released the WCF Express Interop Bindings - a new Visual Studio extension for Soap web services interoperability. If you use Wcf this matters to you!

What did Microsoft release yesterday?

Web services interoperability is always a pain. When security is involved it is usualy more then a casual 'oouch'. Yes, WsHttpBinding has a specific permutation of settings which can interoperate with Oracle web logic. And I know a lot of people who have tried to find that permutation in a brute force manner. Mostly doing this is a waste of time which we prefer to invest in more productive areas.

So here's the idea behind yesterday's shipping: We now have a new binding, WebLogicBinding, which only allow us to configure settings which are interoperable with web logic. So all settings are interoperable! We also have bindings for web sphere, axis2 (wso2) and metro (wsit / glassfigh / tango).
In addition we got a nice wizard on top of Visual Studio's new project dialog which allows us to easily author interoperable services using these bindings.



But don't we already have WS-Policy for interoperability?

WS-Policy helps clients to generate proxies which complies with the service requirements as expressed by the Wsdl. The express bindings solves a prior problem: How to write from the first place a service which a specific client platform can support? Once we write such a service its Wsdl will contain the WS-Policy pixy dust so that the client can auto-configure itself.

Nice... I'll take two!
You can take four: MetroBinding, WebSphereBinding, WebLogicBinding and Wso2InteropBinding.
Take them from here.


Tutorial - WCF and Metro interop

Let's see why web services interoperability just got a whole lot easier.
We'll create a WCF service with mutual x.509 certificates in the message level and consume it with a Metro client.

1. Prepare the environment
You need VS 2010 and the express bindings. After you extract the bindings zip simply execute bin\Microsoft.ServiceModel.Interop.Extension.vsix which will install it on VS.


2. Create a new service

In VS create a new project. Note how the Wcf node now contains a new project type "Express Interop Wcf Service Application":


Choose that project type.

3. Configure the express binding wizard

A few moments after creating the project you will see the wizard.
First choose the platform our clients will use - Metro, this time.


Now we need to configure our security requirements. Choose "mutual certificate" which means both client and server will present an x.509 certificate in the message level. It also implies encryption and digital signature (in this case). To keep it simple we omit the secure conversation.


Next in the advanced settings use the Basic128 algorithm since it is the one Metro supports by default (for Basic256 a patch needs to be applied).


Finally configure the certificate.


I recommend to use this certificate (password: adminadmin):



Now run the service. This is a web site project so it will open the documentation page with the Wsdl link. Make sure to have the Wsdl url handy since we will use it in a moment.



Now we want to configure Metro.

1. Set up the environment

You should have NetBeans 7 (or higher), though NetBeans 6.7 also worked for me.


2. Create a new project of type Java Application:


Any of the default settings are fine:


3. Right click the package in the project view and add a new "web service client":


Now is a good time to paste that Wsdl url:


4. The service reference is now in the project view so right click it and edit the Web Service Attributes (similar to the Wcf configuration... just very different :):


5. This step is a workaround if your NetBeans version ships with Metro 2.0 (which is the case for NetBeans 7). See below how to know if you need it.

We can see that Metro had automatically identified that client and server certificates are required. This was due to the WS-Policy in the Wsdl.

Before we continue we need to do some trick. NetBeans 7 ships with Metro 2.0 which has a bug with certificates. In favor of those who reach this post via a search engine this is the error message:

java.lang.NullPointerException
...
at com.sun.xml.ws.security.impl.policy.CertificateRetriever.digestBST (CertificateRetriever.java:136)

To solve this you need to download Metro 2.1 (or higher). For now just extract it to some folder.

Now as part of this workaround check the "use development defaults" drop down in the quality attributes dialog you opened in step 4. Also approve any message you are prompt with.


Click Ok to close the dialog.

In the project pane expand the libraries node. It should look like this:


This workaround applies to version 2. If you see another version (even smaller) no need for this. What you need to do is delete all the references to Metro jar files (don't delete the jdk though). Instead of them right click the "libraries" node, choose "add jar/folder..." and choose the jar files in metro\bin folder from the metro 2.1 zip you just extracted. Add all jar files in that folder. The libraries node will now look like this:


6. We are now ready to do the actual configuration. Open again the web service quality attribute form as you did in step 4. Uncheck the "use development defaults" check box. Now configure the keystore and trust store. I recommend to use this java key store file:



Open "keystore..." and "Truststore.." each in its turn and do the below.
Set the path to the .jks file you extracted form the certificates file above, set the password to "adminadmin", and click "load alias". The alias for the key store is xws-security-client and for the trust store is xws-security-server.





7. Now we need to write the client code.

Since most of my readers are .Net developers let's see if we can pull this one out without any Java coding at all.

Drag the GetData node from the project pane to the main() method. It should now look like this (depending on the netbeans version):

public static void main(String[] args) {

  try { // Call Web Service Operation
     org.tempuri.Service service = new org.tempuri.Service();
     org.tempuri.IService port = service.getMetroBindingIService();
     // TODO initialize WS operation arguments here
     java.lang.Integer value = Integer.valueOf(0);
     // TODO process result here
     java.lang.String result = port.getData(value);
     System.out.println("Result = "+result);
  }
 catch (Exception ex) {

  }

}


if you use Netbeans 7 it will only generate a method so you would need to add code that calls it:

public static void main(String[] args) {
  try
  {
     String s = getData(2);
     System.out.println("result is" + s);
  } catch (Exception ex) {
     System.out.println(ex.getMessage() + ex.getStackTrace().toString());
  }
}

private static String getData(java.lang.Integer value) {
   org.tempuri.Service service = new org.tempuri.Service();
   org.tempuri.IService port = service.getMetroBindingIService();
   return port.getData(value);
}
}

7. Now run the application (F6).

Here is the output:

the result is: 2


Web services interoperability was never easier!

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

Friday, October 8, 2010

Wcf self hosting - also in VS 2010

@YaronNaveh

A while ago I published a Wcf self hosting template project for visual studio 2008.
The same template also works for VS 2010: just put this under

"%My Documents%\Visual Studio 2008\Templates\ProjectTemplates\Visual C#\WCF"

and the new template is under the C# / Wcf node:



Enjoy :)

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

Sunday, September 19, 2010

What does the Asp.Net security vulnerability mean for Web Services and Wcf?

@YaronNaveh

The "padding oracle" Asp.Net vulnerability will surely affect many production web sites. Does this have any effect on web services and Wcf?

To put this in concrete terms, can a web service become a "padding oracle"?

Without getting too much into details, I believe it is possible in some situations. The best way to protect against this is to ensure all your messages are digitally signed. With Wcf this behavior is actually built in to the framework and you cannot send messages which are encrypted but not signed. With older frameworks such as Wse, and some non-MS soap stacks, this is possible, so you might want to check any relevant production application.


Regardless of this it is always a best practice to sanitize customer facing error messages.

I have actually did a little test. I have configured a Wcf service to emit debug information in error responses (this is the most verbose response Wcf is capable of). I have then created a valid encrypted request, manually altered the encryption to make it not valid, sent it to the server and got this soap fault:

An error occurred when verifying security for the message.


No secret data is enclosed here. I have then changed my server implementation to throw a logical exception:

public string GetData(int value)
{
   
throw new Exception("Data is not available");
}

I initiated a legal request and this time got this response:

<Message>Data is not available</Message>
<StackTrace>
at Service.GetData(Int32 value) in C:\Users\naveh\Documents\Visual Studio 2008\Projects\WCF Self Hosted Service37\WCF Self Hosted Service37\Service.cs:line 23
at SyncInvokeGetData(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
</StackTrace>

So Wcf did return a full stack trace with an application exception. This means that Wcf shields us from verbose errors when security exceptions are thrown.


So are we safe?
You never are. For this reason take these precautions when using Wcf:

Disable debugging information in responses
Even though we saw Wcf tries not to disclose security information you should still protect from such information leaking into application level exceptions (or Wcf bugs). Just make sure your service has this behavior:

 <behaviors>
       
<serviceBehaviors>
         
<behavior name="ServiceBehavior">
              
<serviceDebug includeExceptionDetailInFaults="false" />
          </
behavior>
       
</serviceBehaviors>
     
</behaviors>

Protect your trace files at all cost
They may contain the detailed exceptions hackers look for.

What about Asp.Net web services?
Asp.Net web services (asmx) are inherently insecure (WRT message level) unless Wse is used with them. You should apply the same technique and sanitize your Wse error messages as explained in this walkthrough.

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

Monday, September 6, 2010

Better Username token for WCF

@YaronNaveh

Gerwin Postma had commented on my ClearUsernameBinding post with an interesting link. It seems aszego had published a username token class for WCF which has improved capabilities comparing to the built-in one (in terms of interoperability). Some of the great features are support for digest password and nonce:

<UsernameToken>
...
<Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">S5Of09Zuan02wWpbSEx7EDZsefE=</Password>

<Nonce>Ka+AC6oq5ROJ/pHX1sW+Ng==</Nonce>

</UsernameToken>

This is a great library for many people struggling with ws-security interoperability, although username issues are relatively easy to workaround by writing custom inspectors.

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

Saturday, August 7, 2010

Mime Attachments (Swa) for Wcf

@YaronNaveh

As we know from the web services attachments matrix, Wcf does not natively support Soap With Attachments (SwA, sometimes referred to as Mime attachments). Fortunately some nice people from Microsoft and SVC GmbH. in Austria have published a proof of concept for a Wcf SwA encoder. It does not have a fancy API yet and you would have to hard code your attachments in the encoder code itself. However it is a great start if you need such an interoperability.

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

Tuesday, July 27, 2010

Replay attacks in Wcf (now really)

@YaronNaveh

A few months ago I have written a post about replay attacks in Wcf. One of my readers had sent me a mail mentioning that while that post had some interesting information on replay attacks in general, it did not really discussed the Wcf part. In particular he asked me about the Wcf nonce cache and its difference from the Wse one. Also he was interested in cases where a replay attack may become a DOS attack. Here is what I wrote him back:

Yes, Wcf has a replay cache. One difference from the Wse cache is that in Wcf only the primary signature value is used for cache and not a username nonce (Wcf does not emit these anyway). You might want to take a look at some of the relevant Wcf security settings, for example ReplayCacheSize.
If you are really interested you can open reflector in System.ServiceModel.Security.ReceiveSecurityHeader.ProcessPrimarySignature() and see how the primary signature is validated againt the nonce cache:

...
this.primarySignatureValue = signedXml.GetSignatureValue();
    if (this.nonceCache != null)
    {
        CheckNonce(this.nonceCache, this.primarySignatureValue);
    }
...

As for DOS, the cache comes to solve the problem of replay attackes, e.g. an attacker sends a message a second time which makes a transaction presumably run twice and cause business damage. DOS attacks overloads the server with many requests until it stops from effectively surveying clients. While these attacks are not related, the cache used to prevent replay attacks can become very big until the server is out of memory. This can happen with or without a DOS taking place. For this reason the cache is limited in size and after X minutes a timestamp is used instead. If an attacker can send many non-replay requests in a short time to fill the cache he might be able to actually replay a message before the time windows is closed. However this will not be considered a DOS (even if it is just semantics). Regardless, I am not aware of any way for a web site to protect against a massive DOS attack where bots from around the globe act together.

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

Sunday, July 25, 2010

WCF Gotcha: Binary and MTOM encodings not optimal for untyped scenarios

@YaronNaveh

WCF binary encoding efficiently writes Xml in a binary optimized format. For example, this text message

<s:Envelope …>
  <s:Header> 
    <!-- ws-addressing stuff… -->
   </s:Header> 
  <s:Body>
    <MyContract>
      <arr>
        <b:int>99999</b:int>
        <b:int>99999</b:int>
        <b:int>77777</b:int>
        <b:int>99999</b:int>
      </arr>
    </MyContract>
  </s:Body>
</s:Envelope>

is 1KB in the default text encoding but only half the size in binary (554 bytes). The reasons are various:
  • binary encoding knows to write int values as a one 4-bytes int and not as five 1-byte chars.
  • binary does not repeat the “int” element name more than once.
  • binary does not need to write known elements (e.g. Envelope, Body) but only the key in an optimized dictionary.
The difference is clear if we look at the text and binary messages in Fiddler’s HexView:

(click image to enlarge)

Text

Binary


This code snippet is the one I used to send the above message in a binary format:

[ServiceContract]
    public interface IUniversalContract
    {
        [OperationContract(Action = "*", ReplyAction = "*")]
        Message Send(Message message);
    }
    [DataContract]
    class MyContract
    {
        [DataMember]
        public int[] arr;          
    }
private static IUniversalContract GetChannel()
        {
            var binding = new CustomBinding();
            binding.Elements.Add(new BinaryMessageEncodingBindingElement());
            binding.Elements.Add(new HttpTransportBindingElement());
            var factory = new ChannelFactory<IUniversalContract>(binding);
            return factory.CreateChannel(new EndpointAddress("http://localhost:8888/"));
        }
static void Main(string[] args)
        {
var channel = GetChannel();
var obj = new MyContract { arr = new[] { 99999, 99999, 77777, 99999 } };                       
            Message msg = Message.CreateMessage(MessageVersion.Soap12WSAddressing10, "someAction", obj);
            channel.Send(msg);
}

You can see I have built a custom binding which uses the binary encoding. Then I have instantiated my data contract class and sent it.

But take a look at this code:

static void Main(string[] args)
        {
var channel = GetChannel(); //same method as above

var str =
                new StringReader(
                    @" <MyContract xmlns=""http://schemas.datacontract.org/2004/07/ConsoleApplication288""
xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><arr xmlns:b=""http://schemas.microsoft.com/2003/10/Serialization/Arrays""><b:int>99999</b:int>
<b:int>99999</b:int><b:int>77777</b:int>
<b:int>99999</b:int></arr></MyContract>");
          
            XmlReader reader = XmlReader.Create(str);
            Message msg = Message.CreateMessage(MessageVersion.Soap12WSAddressing10, "someAction", reader);
            channel.Send(msg);
}

It sends the same message on the wire but uses a raw xml message instead of a live object. This is common in routing scenarios, in cases where the message is manually handcrafted and in places where message is taken from an external source.

Let’s see how this message looks like in Fiddler:



its size is 577 bytes which means it has 23 extra bytes over the object-based binary message. While this seems negligible, had we sent more array elements, and had the integer values require additional digits, the difference would be very noticeable, especially for an optimized format. For example, with just 50 items in the array the second message was already 2.5 times larger the the fully optimized one.

So from where does this difference come from? when analyzing the raw messages we find two interesting differences:
  • In the less optimized message the text “int” repeats a few times where in the optimized one it only appears once. As far as I understand this text here represents the array element name and not the fact that the type is an int.
  • In the less optimized message the array values are written as five 1-byte chars (=5 bytes per value) whereas in the optimized message they are a one 4-byte integer (=4 bytes per value). For higher integers the difference is bigger and for long arrays the difference is huge.
The second difference is understandable – the binary encoder does not have type information since it only gets a big string as input. It then cannot optimize integers. I’m not really sure however as for the first issue – maybe the reason is that for integers we do not need array items separator as values are of fixed types whereas for strings we need to know when the string has ended. But still I would expect a more optimized separator so I’m not really sure about this one.


Conclusion

Wcf binrary encoding is a popular optimization technique, especially ever since it became available to Silverlight applications. However, When untyped messages are used, binary encoded messages are less optimal than in the typed scenarios. They are still more optimal than regular text encoded messages. The same corollary can be reached for MTOM scenarios as they use the same optimization technique. If you use such messages (usually in routing scenarios) you should be aware of this and consider the different trade-offs.

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

Sunday, June 27, 2010

Wcf interoperability wish list

@YaronNaveh

If you have already filled your duty please share it in the comments. Here is my take.

My WCF 4.0+1 interoperability wishlist:

  • Be more forgiving. In so many cases I have sent a good request to the server, got a correct response, and had to workaround a non happy proxy complaining on "timestamp missing in the response", "expected to get serialized token" etc. If I do not explicitly require this I do not want Wcf to do it for me.

  • Low level extension point. Ok, so I got a wrong certificate reference from the other party, I just need to change it in the incoming message so Wcf will not throw some exception. I googled for "changing wcf message" and got a nice link about message inspector. Too bad it cannot change the security applied message. I had to use a custom encoder, which is really much harder to implement / maintain.

  • Better error messages. When you compile a VS project you sometimes get an error message like this:


    The type X could not be found (are you missing an assembly reference?)


    I wish Wcf would also have this. For exmple:


    The EncryptedKey clause was not wrapped with the required encryption token 'System.IdentityModel.Tokens.X509SecurityToken'. Are the client and server certificates in sync?


    I have actually posted a series of posts titled "Cryptic WCF error messages" which tries to supply the most common cause for many errors.

  • Better trace / debug. Wcf trace is really great and today we can already debug into the framework. So what do I want here? I'm not sure yet, I just know these are essential tools for interoperability and I want them easier and better.


    And more...

    In addition there are some lower level requirements that are not supported today. Not all are priority zero, but I have seen all of them in interoperability scenarios.

  • Encrypting / Signing specific elements in the message body (e.g. using xpath)

  • Control over xml signature algorithm / transformations

  • Support of the DSA algorithm

  • User / Pass authentication at the message level with a password hash + control over the nonce / created fields

  • WS-Addressing August 2004

  • Mime, SwA, Dime (probably a bigger effort than the others...)

  • Control over the security element mustUnderstand attribute

  • Native support for JKS (Java Key Store)

  • Keeping alive binding converter from the evil Azure trial expiration...

  • Some people require to use specific namespace prefixes in their Xml. Don't ask me what is it good for, but Wcf should allow it. I have seen this especially in interoperability scenarios.

  • Better coverage of wsdls - even today not all are parsed or pass code generation. Some examples last back to the old the 2.0 days and are easy to identify and fix.

    I'm pretty sure I have more somewhere but this should be enough for one version :)

    @YaronNaveh

    What's next? get this blog rss updates or register for mail updates!
  • Sunday, June 20, 2010

    Wcf Interoperability Survey

    @YaronNaveh

    Microsoft has published an online survey on web services interoperability using Wcf . If you have ever surved / consumed Wcf from another platrofm (including .Net 2.0) you probably have one or two pains to share. This survey is your chance to be heard.

    @YaronNaveh

    What's next? get this blog rss updates or register for mail updates!

    Friday, June 18, 2010

    Wcf Security Interoperability Series

    @YaronNaveh

    If you are a fan of Wcf security interoperability blogs - and if you read my blog you must admit you secretly are - you do not want to miss dhurba's series on WCF security interoperability.

    As a side note, in the last weeks there is a bug with MSDN hosted blogs (as dhurba's) where I am sometimes prompted for a password when surfing there. This mostly happens with Chrome, but sometimes also in IE. This is usually solved by restarting the browser (better chances with IE) but is really annoying.

    @YaronNaveh

    What's next? get this blog rss updates or register for mail updates!

    Tuesday, April 20, 2010

    Interoperability Gotcha: OAEP Parameterization is not supported

    @YaronNaveh

    WSE2 is already obsolete but I still see people trying to reach interoperability from WSE2 to WCF. Surprisingly there are a number of interesting ws-security scenarios where this is possible. Today I will discuss one scenario where it may be harder.

    WSE configuration allows to configure the algorithms we use for encryption:


    <microsoft.web.services2>
    ...
         <keyAlgorithm name="RSA15" />
    ...
    </microsoft.web.services2>


    Some scenarios work great with RSA15 but when we change it to RSAOAEP we may see this exception from the WSE party:


    OAEP Parameterization is not supported


    Let's see what in the message that WCF sent to WSE may cause this:


    <e:EncryptedKey xmlns:e="http://www.w3.org/2001/04/xmlenc#">
      <e:EncryptionMethod   Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p">
          <DigestMethod       Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"       xmlns="http://www.w3.org/2000/09/xmldsig#" />
      </e:EncryptionMethod>
    </EncryptedKey>


    We can see that the encryptedKey is indeed encrypted with the RSAOAEP algorithm. Also the RSAOAEP RFC states that:


    The RSAES-OAEP-ENCRYPT algorithm... takes three parameters. The two user specified parameters are [MANDATORY]... The message digest function is indicated by the Algorithm attribute of a child ds:DigestMethod element...


    Hence the DigestMethod element.

    So why WSE throws an exception when a mandatory parameter is specified? Let's look at a WSE generated message to see if it produces anything different:


    <e:EncryptedKey xmlns:e="http://www.w3.org/2001/04/xmlenc#">
      <e:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p">
        <ds:DigestMethod     xmlns:ds="http://www.w3.org/2000/09/xmldsig#"     Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
      </e:EncryptionMethod>
    </EncryptedKey>


    Looks the same to me. So let's drill down into the WSE stack to understand the root cause. The error seems to be thrown from within this method:


    public override void set_Parameters(string value)
    {
       if (((value != null) && (value.Length != 0)) && (value != this._parameters))
       {
         throw new NotSupportedException("OAEP Parameterization is not supported");
       }
    }


    Ok so we are comparing the current message parameters (value) to some default value (this._parameters). But what is this default? Let's look in the ctor:


    public RSAOAEPKeyExchangeFormatter()
    {
       this._parameters = "";
    }


    Oh boy. WSE2 compares xml fragments as strings! So it sees this:


    <DigestMethod xmlns="http://www.w3.org/2000/09/xmldsig#" />


    as different from this:


    <ds:DigestMethod xmlns:ds="http://www.w3.org/2000/09/xmldsig#" />


    While the above fragments have the same xml semantics.

    Just in order to convince my self this is the issue, I have manually changed the soap so that it will have the WSE-style digest. This worked like a charm. This kind of gives us the general solution here which is to build a WSE filter that changes the soap format to the one WSe expects. Note that you can only change non-signed soap parts, which is usually the case with the encrypted key. The easier option of course is to revert to the RSA15 algorithm.

    And let's not forget the main point which is to never compare xml as a string.

    @YaronNaveh

    What's next? get this blog rss updates or register for mail updates!

    Sunday, April 4, 2010

    Wcf first connection is slow

    @YaronNaveh

    You may have experienced the first connection from a Wcf client to a service to be extremely slow. In some cases this is expected as the first connection establishes a session which may require exchange of multiple messages. However in some cases there is no obvious reason for that.

    One cause may be a slow http proxy. By default, Wcf uses the default http proxy configured in internet explorer. The proxy may be specified directly or in form of a configuration script:





    If this is the cause of the slowness you can reproduce it by surfing to any site using a new IE instance - same slowness should occur.

    The possible solutions are:

    1. Remove the proxy configuration from IE.
    2. Configure your WCF binding with UseDefaultProxy=false.

    @YaronNaveh

    What's next? get this blog rss updates or register for mail updates!

    Tuesday, March 23, 2010

    Customizing ClearUsernameBinding

    @YaronNaveh

    ClearUsernameBinding has became very popular recently and many people ask how to modify it for their needs. Most people want to increase message size quotas but there are definitely other required customizations.

    Suresh has written a nice post on how to increase some of the message quotas. Also the comments to the original post contain more useful information.

    Generally speaking, most customizations can just imitate the way messageVersion is handled, so just search for wherever this string appears (5 places) and add you equivalnet code for what you are customizing. Hopefully soon I'll publish a concrete example.

    @YaronNaveh

    What's next? get this blog rss updates or register for mail updates!

    Monday, March 22, 2010

    Wcf: "The security capabilities do not match the generated runtime object"

    @YaronNaveh

    The below Wcf error message is quite rare. You would encounter it only when developing some specific kinds of Wcf custom channels and transports.


    The security capabilities of binding
    'System.ServiceModel.Channels.CustomBinding' do not match those of the generated runtime object. Most likely this means the binding contains a StreamSecurityBindingElement, but lacks a TransportBindingElement that supports Stream Security (such as TCP or Named Pipes). Either remove the unused StreamSecurityBindingElement or use a transport that supports this element.

    at

    System.ServiceModel.Channels.Binding.
    ValidateSecurityCapabilities(ISecurityCapabilities runtimeSecurityCapabilities,
    BindingParameterCollection parameters)


    When you develop a custom channel you usually develop one class which derives from BindingElement and another which implements IChannelFactory. Both classes have this method:


    public virtual T GetProperty()


    In many cases you override this method to return a specific set of ISecurityCapabilities. One example use case is ClearUsernameBinding:


    public override T GetProperty(BindingContext context)
    {
       if (typeof(T) == typeof(ISecurityCapabilities))
         return (T) (ISecurityCapabilities) new AutoSecuredHttpSecurityCapabilities();

       return base.GetProperty(context);
    }


    In runtime, Wcf verifies that the capabilities the factory claims it can support are also supported by the actual channel. In other words this must be true:

    channel.GetProperty()==factory.GetProperty()

    If you have override the GetProperty() method of the channel but not of the factory then you will get the error above.

    @YaronNaveh

    What's next? get this blog rss updates or register for mail updates!

    Saturday, March 20, 2010

    Wcf Binding Box: Security usage patterns

    @YaronNaveh

    WCF Binding Box is on air for over six months now. Hopefully it will stay there for a while, at least until Azure will close the free trial period. For those of you who forgot, the binding box allows to convert any WCF binding (e.g. WSHttpBinding) to a CustomBinding.

    Around 1500 users have converted their bindings already. This seems like a good time to analyze some WCF security usage patterns.


    Message Security Type

    The first aspect I analyzed is the security type people use. Results show that over 60% of users apply some message level security (possibly together with ssl). One possible explanation to this result is that message level security is the default with Wcf (in contrary to most legacy soap stacks). Another explanation is this: People who work with message level security have much more available configurations, so they seek the binding box in order to get a custom binding. This means the measurement here may be a little biased.

    (click image to enlarge)




    Client Credential Type (Message)

    The second question I tested is which message credentials are most popular. The results show that username authentication is by far the most popular authentication mechanism. This is expected considering that usernames are the easiest to work with and offer the best interoperability. We can tie this together with the huge interest in ClearUsernameBinding. Windows authentication gets a relatively low share which may indicate that most binding box users wrote internet and not intranet applications.

    (click image to enlarge)




    Client Credential Type (Transport)

    Finally I have tested which are the most popular client authentication types with transport security. Here domain based authentication (windows, ntlm) is used by almost 40% of the users. Basic authentication is only 15% which is surprising taking into consideration that the most popular message level authentication mechanism is a UserName token. A quarter of the users chose the Certificate authentication type. We can add to this the fact that client certificates have a similar message level share, and that server side certificates are used in all of the transport modes and in most message level modes. This shows that most organizations deal with X.509 certificates this way or the other.

    (click image to enlarge)

    @YaronNaveh

    What's next? get this blog rss updates or register for mail updates!

    Saturday, March 13, 2010

    Programatically install SSL for WCF self hosting

    @YaronNaveh

    When we use SSL with IIS deployed services we can configure SSL in the IIS console. But what to do when we self host our service?

    Here's one way to do it (vista / windows 7 / windows 2008 server only).

    Run this command line:


    netsh http add sslcert ipport=0.0.0.0:8732 certhash=4f35f9386692f45b6cc35b7e786c9f06625b9567 appid={00112233-4455-6677-8899-AABBCCDDEEFF}


    Where:


    ipport - The port on which you want to install SSL. The zeros stand for the local machine and 8732 is the port.

    appid - any unique GUID should do it here.

    certhash - The thumbprint of our certificate. See below how to get it.


    How to get the certificate hash / thumbrpint?

    1. Run mmc and add the certificates snap-in.
    2. Double click your certificate and see its thumbprint (hash):



    3. Convert the base64 representation to Hex - this is the value you need.

    From code...

    Now in many cases you will want to do the installation dynamically at run time. This is as easy as:


    using System.Diagnostics;

    ...

    void RunCommandLine(string filePath, string arguments)
    {
         var p = new Process();
         p.StartInfo = new ProcessStartInfo(filePath, arguments);
         p.StartInfo.UseShellExecute = false;
         p.Start();
         p.WaitForExit(10000);
    }

    ...

    RunCommandLine(
       "netsh",
       "http add sslcert ipport=0.0.0.0:8732   certhash=4f35f9386692f45b6cc35b7e786c9f06625b9567 appid={00112233-4455-  6677-8899-AABBCCDDEEFF}");

    @YaronNaveh

    What's next? get this blog rss updates or register for mail updates!

    Saturday, February 27, 2010

    .Net / Wcf bug: Cannot convert type 'System.DateTime[]' to 'System.DateTime'

    @YaronNaveh

    A common bug in .Net 2.0 may cause the following exception when compiling a proxy:

    Unable to generate a temporary class (result=1).

    error CS0030: Cannot convert type 'System.DateTime[]' to 'System.DateTime'

    error CS0030: Cannot convert type 'System.DateTime[]' to 'System.DateTime'

    error CS0029: Cannot implicitly convert type 'System.DateTime' to 'System.DateTime[]'

    Microsoft did not fix this bug for Wcf so it also gives a similar exception:

    There was an error in serializing body of message myRequest: 'Unable to generate a temporary class (result=1).
    error CS0030: Cannot convert type 'System.DateTime[]' to 'System.DateTime'
    error CS0030: Cannot convert type 'System.DateTime[]' to 'System.DateTime'
    error CS0029: Cannot implicitly convert type 'System.DateTime' to 'System.DateTime[]'
    error CS0029: Cannot implicitly convert type 'System.DateTime' to 'System.DateTime[]'
    '.  Please see InnerException for more details.

    Is this error limited to DateTime?

    Not at all. You may also get any of these:

    Cannot convert type 'System.String[]' to 'System.String'

    Cannot convert type 'System.Int32[]' to 'System.Int32'

    Cannot convert type 'System.Decimal[]' to 'System.Decimal'

    Or with your custom types.

    What does this error mean?

    For you – nothing. This is a .Net/Wcf bug.

    When does this happen?

    When the following conditions apply:

    1. The wsdl (schema) declares a complex type C.
    2. C contains a single element with maxOccures>1 (an array).
    3. The wsdl declares an element e of type X with maxOccures>1.

    Example:

      <xsd:complexType name="C">
        <xsd:sequence>
          <xsd:element maxOccurs="unbounded" minOccurs="0" name="someDate" type="xsd:date"/>    
        </xsd:sequence>
      </xsd:complexType>

    ...

    <xsd:element maxOccurs="unbounded" minOccurs="0" name="e" type="tns:C"/> 

    What is the .Net bug?

    The proxy will generate something like this:

            [XmlArrayAttribute]
            [XmlArrayItemAttribute("someDate", typeof(DateTime))]
            public DateTime[][] C {
            ...
            }

    This line declares an array of type DateTime[][], but also specifies that each item of the array is of type DateTime. Which is clearly an error since the array items are of type DateTime[] (this is a multidimentional array).

    This is the reason why the proxy does not compile.

    Workaround #1

    Manually edit the proxy and change “typeof(DateTime)” to “typeof(DateTime[])”. This workaround is also described here.

    Limitation: This change will be overridden every time you regenerate the proxy (update web/service reference).

    Workaround #2

    We mentioned that the bug only happens when the type C has one child element. Why not add it some friend so it would not be alone? This means we need to manually edit the wsdl. For example:

    <xsd:complexType name="C">
        <xsd:sequence>
          <xsd:element maxOccurs="unbounded" minOccurs="0" name="someDate" type="xsd:date"/>          
    <xsd:element minOccurs="0" name="dummyFriend" type="xsd:string"/>     
        </xsd:sequence>
      </xsd:complexType>

    Now you may say this changes the schema and makes our proxy not valid. But note we have added an optional field only (minOccurs=0) so as long as we do not assign any value to it in our client this change is non-breaking.

    Now let’s see how the proxy generated from the updated wsdl looks like:

    public partial class C {
            [XmlElementAttribute("dateValue", DataType="date")]
            public DateTime[] dateValue {
                ...
            }

        [XmlElementAttribute]
            public string dummyFriend {
                ...
            }
        }

    Now .Net does not generate the multidimensional array in one shot, but declares the mediating type C.  The proxy will in turn use this type as an array:

    public C[] e {…}

    which gives us the multidimensional effect.

    This compiles immediately so we’re free to go.

    @YaronNaveh

    What's next? get this blog rss updates or register for mail updates!

    Friday, January 8, 2010

    Replay attacks in Wcf

    @YaronNaveh

    One important attack against web services is a "replay attack": a malicious man-in-the-middle captures a valid message from a client to a server and resends it. This can cause duplicate transactions or denial of service (DOS).

    Typically the way to protect here is to have a timestamp on the message and some expiration policy on the server. This is a very simplified description though, here are all the details.

    The sending party attaches this timestamp to the SOAP message:


    <wsu:Timestamp>
       <wsu:Created>2006-02-22T09:56:27Z</wsu:Created>
       <wsu:Expires>2006-02-22T10:01:27Z</wsu:Expires>
    </wsu:Timestamp>


    The receiving party can then decide based on some policy how much after the message was created it is suspected as a replay.

    But what is this service policy? We can see an "expires" element in the client message itself, then why does the service need an additional policy?

    The answer is that there is a duplicate protection against replay attacks. The client can decide its own policy and express it inside the message. The server should respect this policy and also adds its own policy. For example:


  • Client sends a message in 15:00

  • Client expiration policy is set to 15:05

  • Service gets the message in 15:06

  • Service expiration policy is set to 15:07



  • In this case the message is considered valid by the service, but the service is expected to respect the client policy and reject the message. the situation gets more interesting when we add real network latency and clocks synchronization into the picture.

    In Wcf there are two somehow confusing settings to control the expiration:


  • LocalServiceSecuritySettings.ReplayWindow - The service expiration policy.

  • LocalclientSecuritySettings.TimestampValidityDuration - The client expiration policy as expressed in the message itself.


  • There are various other settings which relate to tolerance for clock differences and I will write a separate post on them some other time.

    @YaronNaveh

    What's next? get this blog rss updates or register for mail updates!

    Wednesday, January 6, 2010

    WCF Binary-encoded Message Inspector for Fiddler

    @YaronNaveh

    We all love our Fiddler. It is a great Http proxy to use when debugging web services (and html). Fiddler now has a WCF binary encoding message inspector. It allows us to see in clear xml binary messages. This is very usefull especially since binary encoding is the default setting for Silverlight 3 applications.

    @YaronNaveh

    What's next? get this blog rss updates or register for mail updates!

    Axis2 & Wcf Interoperability

    @YaronNaveh

    Recently I had to consume an Axis2 web service using a Wcf client. Axis2 used the rampart module for message security where a mutual X.509 certificate was required. Since I had control over both client and server I was able to fine tune them to reach perfect interoperability.

    On the Axis side, I have found the WS-Policy flavor configuration better to work with (interoperability-wise) .

    This is the Axis configuration:



    and this is the Wcf configuration:



    Here is the full Axis2 service (which is based on the rampart SDK sample):



    and the wcf client:



    You will also need certificates.

    Client certificate:



    Server Certificate:



    If prompt for a password use "adminamdin".

    This is the Java key store:



    and the password is "adminadmin".

    If you want to use your own certificate just make sure the certificates have an SKI.

    @YaronNaveh

    What's next? get this blog rss updates or register for mail updates!