Category Archives: Uncategorized

.NET XML Validation Pitfall

XML Schema validation for XML documents using .Net can be a tricky business sometimes. To give you an idea, have a look at the following example.

Example

We have a customer’s details in a XML document: [Customer.xml]

<?xml version="1.0" encoding="utf-8"?>
<customer xmlns="http://bluechaos.be/customers">
  <name>Dirk Vanderbist</name>
  <address>Wetstraat 9</address>
  <city>Brussels</city>
  <country>Belgium</country>
  <businessID>123321</businessID>
</customer>

Furthermore we have a XML Schema to validate the customer against: [Customer.xsd]

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="customer">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="name" type="xs:string"/>
        <xs:element name="address" type="xs:string"/>
        <xs:element name="city" type="xs:string"/>
        <xs:element name="country" type="xs:string"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Who thinks that the customer above is valid according to the schema? Just raise your hand.

For those that spotted the businessID element which is not mentioned in the schema, I have bad news.  The document is considered valid!

Why?

The XML document uses a namespace, i.e. http://bluechaos.be/customers, which is not referenced by the XML schema. Because of that the schema does not see any element it has to validate. So according to the schema the document is valid!

To avoid this situation you should check if the namespace used by the Xml document and Xml schema match.

Codesample

I wrote a small code sample to show how it can be done. The principal logic takes place in the CheckNamespace and CheckStructure methods. The CheckNamespace verifies if the schema has at least something to validate to overcome overlooking the missing namespace like what happened in the example above. The CheckStructure method does the actual schema validation.

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.IO;
using System.Xml.XPath;

namespace Validate
{
    class Program
    {
        private static List<Exception> validationErrors = new List<Exception>();

        static void Main(string[] args)
        {
            if (args.Length == 2)
            {
                // parse and check arguments
                string xmlFile = args[0];
                string xsdFile = args[1];
                if (!File.Exists(xmlFile)) Console.WriteLine("XML file does not exists");
                if (!File.Exists(xsdFile)) Console.WriteLine("XSD file does not exists");

                // validate xml document
                if (Validate(xmlFile, xsdFile))
                {
                    Console.WriteLine("VALID");
                }
                else
                {
                    Console.WriteLine("INVALID");
                }
            }
            else
            {
                ShowUsage(); // show the required arguments
            }

            Console.WriteLine("Press Enter to Exit...");
            Console.ReadLine();
        }

        static private void ShowUsage()
        {
            Console.WriteLine("validate [XmlFile] [SchemaFile]");
            Console.WriteLine("\t [XmlFile] Xml doocument to validadate");
            Console.WriteLine("\t           e.g. input.xml");
            Console.WriteLine("\t [SchemaFile] Xsd schame used to validadate");
            Console.WriteLine("\t           e.g. schema.xsd");
        }

        static private bool Validate(string xmlFile, string xsdFile)
        {

            if (CheckNamespace(xmlFile, xsdFile) && CheckStructure(xmlFile, xsdFile))
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        static private bool CheckNamespace(string xmlFile, string xsdFile)
        {
            // check if namespace match
            XPathNavigator xmlnav = new XPathDocument(xmlFile).CreateNavigator();
            xmlnav.MoveToFollowing(XPathNodeType.Element);
            string documentNamespace = xmlnav.GetNamespace("");

            XPathNavigator xsdnav = new XPathDocument(xsdFile).CreateNavigator();
            xsdnav.MoveToFollowing(XPathNodeType.Element);
            string schemaNamespace = xsdnav.GetNamespace("");

            if (documentNamespace != schemaNamespace)
            {
                Console.WriteLine("Namespace mismatch xml:'{0}'<>xsd:'{1}'",
                 documentNamespace, schemaNamespace);
                return false;
            }
            else
            {
                Console.WriteLine("Namespace match xml:'{0}'==xsd:'{1}'",
                 documentNamespace, schemaNamespace);
                return true;
            }
        }

        static private bool CheckStructure(string xmlFile, string xsdFile)
        {
            // validate xmlFile against schema
            try
            {
                XmlTextReader reader = new XmlTextReader(xmlFile);
                XmlReaderSettings readerSettings = new XmlReaderSettings();
                readerSettings.ValidationType = ValidationType.Schema;
                readerSettings.Schemas.Add(null, xsdFile);
                readerSettings.ValidationFlags = XmlSchemaValidationFlags.None;
                readerSettings.ValidationEventHandler += new ValidationEventHandler(ValidationEvent);

                XmlReader xmlReader = XmlReader.Create(reader, readerSettings);

                while (xmlReader.Read()); //Read through the document
                xmlReader.Close();

            }
            catch (Exception e)
            {
                Console.WriteLine("Exception occured: " + e.Message);
                return false;
            }

            if (validationErrors.Count > 0) return false;
            return true;
        }

        // validate callback event
        static private void ValidationEvent(object sender, ValidationEventArgs ve)
        {
            // add exception to exeception list and dump to console
            validationErrors.Add(ve.Exception);
            Console.WriteLine(ve.Exception);
        }
    }
}

To Conclude

You should remember to check the namespaces if it looks like your XML Schema validation is doing nothing.

Share this postSave this post

Common Weakness Enumeration

Common Weakness Enumeration (CWE) is a list containing the top 25 most dangerous programming errors that can lead to serious software vulnerabilities.

You can find the list at: http://cwe.mitre.org/top25/

It should be common sense for every programmer but still software is released violating these basic rules. The list serves as reminder for senior developers and can be used as a checklist by CIO’s. For junior developers it can be considered as a reference of good practices and pitfalls to avoid.

SQLInjection

Share this postSave this post

Firewall Architecture

Below I present a basic overview of firewall architecture. I created this as a reference document in the case the LAN-guys are barking network stuff to me on a project I’m working on.

The untrusted network in the diagrams you can interpret as the Internet and the trusted network you can read as the intranet or the company’s LAN.

Packet Filtering Router
PacketFilteringRouter_resize

The Packet Filtering Router screens the packets exchanged between the untrusted and trusted network. Basic routers cannot do much more then routing traffic and do only support basic rulesets. Basic rules are for example indentifying subsets of ip-addresses that are allowed to communicate between the untrusted and trusted network.

More elaborate rulesets allow for filtering based on the detailed content of the ip-packages. In the latter case the router is sometimes called a firewall.

Bastion Host or Screened Host
BastionHost_resize
Incomming traffic, from the untrusted network, is forwarded to the bastion host server or firewall that will determine whether or not the messages are forwarded to the trusted network.
Outgoing communication can follow the reversed route or can go directly from the trusted to the untrusted network bypassing the bastion host.

Dual-Homed Gateway
DualHomedGateway_resize
The gateway has two network interfaces and sits between the trusted and untrusted network. Direct forwarding on the network interfaces is blocked to force the traffic to go through an application or proxy running on the gateway. The application will connect to the two networks.

Demilitarized Zone (DMZ) or Screened Subnet
DMZ_resize
Here we have a set of two routers creating an additional network, in between the trusted and untrusted network, called the DMZ.

The traffic destined from the trusted network to the untrusted network is routed directly through the two routers or goes to the firewall and is forwarded to the untrusted network from there.

Traffic from the untrusted network to the trusted network is sent first to the firewall in the DMZ and is then forwarded to the trusted network.

Public accessible servers (for example webservers) are located in the DMZ and the traffic is routed from the untrusted network directly to those servers.

The major difference between this architecture and the Bastion Host is that the Bastion Host would have had to combine the functionality ran on the public servers and the traffic forwarding functionality.

Firewall Appliance
Firewall_resize
This is piece of hardware with multiple network interfaces that allows it to connect to multiple subnets, i.e. the gateway functionality like with dual-home gateway, and do intelligent packet filtering.

Proxy
If the traffic from the trusted network to the untrusted network is forced to go through one location in the DMZ, it is possible to introduce some additional functionality like:

  • hiding the ip-addresses from clients in the untrusted network (anonymizing requests)
  • caching request from multiple client in the trusted network to the same source in the untrusted network

If the proxy does this in such a way that exchanged messages are not modified, we say it is a tunneling proxy sometimes called a gateway.

Some of the proxies are transparent for the client in the untrusted network. This has the advantage that the clients are unaware of it and do not require any configuration. For anonymization this is not possible because the proxy needs to modify the message exchanged between the trusted and untrusted network.

Reverse Proxy
Here a proxy is acting on traffic coming from the untrusted network destined to the public accessible servers in the DMZ. The reverse proxy can provide following additional functionality transparently for the clients in the untrusted network:

  • load balancing the incoming request transparently over multiple servers
  • terminating secure communication or decrypting encrypted messages, to take away this burden from the public accessible servers behind it
  • caching frequently requested information
Share this postSave this post

Kerberos Helper Tool

When reading up on Kerberos security I found a nice tool that helps you with the tedious job of getting the Service Principal Names (SPN) right. It is called Kerberos SPN Viewer and Helper Tool. You can download it from msdn blogs. It was just released in a post a few days ago!
Cerberus
A good summary how Kerberos works, I found it in the following location: http://www.xml-dev.com/blog/?action=viewtopic&id=21 or as a Kerberos.

For the reasons why why we need SPN-s a quick introduction is written on Keith Guidebooks’ under: http://alt.pluralsight.com/wiki/default.aspx/Keith.GuideBook/WhatIsAServicePrincipalNameSPN.html. The PDF version of that page.

Share this postSave this post

Exploring the Continuum of Test Doubles

Introduction
When implementing an application dealing with time conversion related logic, UTC-0 time to local time and vice versa, it became clear that testing was of the essence. The behavior around daylight saving time (DST) switches was something that required complex tests. At that moment I started reading about the different kind of unit tests I could use.

I required test objects that could stand in for the actual .NET DateTime class to simulate the time during DST switches, without having to change the server’s time. In testing theory these are called test doubles which resembles very closely the image of car tests-dummies. We ended up using Rhino Mocks.

During my literature research I found an article that was published in MSDN Magazine in 2007 by Mark Seemann describing the spectrum of test doubles going from absolute no implementation on the one end to fully implemented objects on the other end.

The article was very valuable to me and you can find the full version by going to http://msdn.microsoft.com/en-us/magazine/cc163358.aspx. Here you?l find a concise summary.

The spectrum
testspectrum
The following test doubles are identified in the spectrum, below we?l discuss them one by one:

  • Dummies
  • Stubs
  • Spies
  • Fakes
  • Mocks
    • Manual Mocks
    • Automatic Mocks

Dummies

Dummies are the most basic test doubles. Dummies just avoid compile time errors by complying with method signatures and interface implementations but are useless at run time.

This is the effect you get when you use the implement interface command in Visual Studio. For example:

public interface IShopDataAccess
{
    decimal GetProductPrice(int productId);
    void Save(int orderId, Order o);
}
public void Save(int orderId, Order o)
{
    throw new Exception("The method or operation is not implemented.");
}

It is very clear you should never call the Save method although the code compiles perfectly.

Stubs

Stubs are evolved versions of Dummies so that at least at runtime no exceptions are thrown.

In our example the Save method returns no result so avoiding run-time exceptions can be simply done by having an empty method implementation:

public void Save(int orderId, Order o) { }

If the method would return values we can just hard-code these values.

public decimal GetProductPrice(int productId)
{
	return 25
}

But very fast we end up with a tree of if-statements returning different values based on the Id that is passed as a parameter. Although it is useful, this is not a very flexible solution.

public decimal GetProductPrice(int productId)
{
    switch (productId)
    {
        case 1234:
            return 25;
        case 2345:
            return 10;
        default:
            throw new ArgumentException("Unexpected productId");
    }
}

Spies

The purpose of test dummies in general is to demonstrate that the test target works as intended. With Dummies and Stubs it is hard to argument they demonstrate anything.

Spies add the ability to see whether or not a certain method was called and the parameters it was called with.

internal class SpyShopDataAccess : IShopDataAccess
{
    private bool saveWasInvoked_;

    #region IShopDataAccess Members

    // Other IShopDataAccess members ommitted for brevity

    public void Save(int orderId, Order o)
    {
        this.saveWasInvoked_ = true;
    }

    #endregion

    internal bool SaveWasInvoked
    {
        get { return this.saveWasInvoked_; }
    }
}

Fakes

To avoid if-then-hierarchies to return values like with Stubs, we could create an in memory database based on collections. This allows for more realistic results to be returned with more flexibility then a fixed list in the method itself.

The Fake could be programmed as follows:

internal class FakeShopDataAccess : IShopDataAccess
{
    private ProductCollection products_;

    internal FakeShopDataAccess()
    {
        this.products_ = new ProductCollection();
    }

    #region IShopDataAccess Members

    public decimal GetProductPrice(int productId)
    {
        if (this.products_.Contains(productId))
        {
            return this.products_[productId].UnitPrice;
        }
        throw new ArgumentOutOfRangeException("productId");
    }

    public void Save(int orderId, Order o) { }

    #endregion

    internal IList<Product> Products
    {
        get { return this.products_; }
    }
}

The test data is populated through the test class that will be calling the Fake during the test. For example:

public void CalculateLineTotalsUsingFake()
{
    FakeShopDataAccess dataAccess = new FakeShopDataAccess();
    dataAccess.Products.Add(new Product(1234, 45));
    dataAccess.Products.Add(new Product(2345, 15));
    ...    // remainder of the  test code
    ...}

The trouble with this approach is that creating Fakes requires almost as much work as writing the code we are testing.

If the code for the test doubles is becoming more and more complex you?e probably overdoing it. If you start thinking about testing your test doubles you simply went too far.

Mocks

Mocks are libraries that support the creation of Dummies, Stubs, Spies and Fakes. Libraries can be reused to avoid repeating tedious programming.

Manual Mocks

Creating your own mocking libraries, i.e. Manual Mocks, isn’t a walk in the park.

A Manual Mock could look like this:

internal class MockShopDataAccess : IShopDataAccess
{
    private ImplementationCallback implement_;

    internal MockShopDataAccess(ImplementationCallback callback)
    {
        this.implement_ = callback;
    }

    #region IShopDataAccess Members

    public decimal GetProductPrice(int productId)
    {
        MemberData member = new MemberData("GetProductPrice");
        member.Parameters.Add(new ParameterData("productId", productId));

        this.implement_(member);

        return (decimal)member.ReturnValue;
    }

    public void Save(int orderId, Order o)
    {
        MemberData member = new MemberData("Save");
        member.Parameters.Add(new ParameterData("orderId", orderId));
        member.Parameters.Add(new ParameterData("o", o));

        this.implement_(member);
    }

    #endregion
}

The important part is situated in the GetProductPrice method were a delegates is called to retrieve a value. This delegate must be implemented in the test class and will be called back from the Manual Mock. In order for the Manual Mock to be aware what delegate to call, it is passed in the constructor.

The test class needs an implementation for the delegate. We could use an inline delegate definition for this:

public void CalculateLineTotalsUsingManualMock()
{
    MockShopDataAccess dataAccess =
        new MockShopDataAccess(delegate(MemberData member)
    {
        if (member.Name == "GetProductPrice")
        {
            int productId = (int)member.Parameters["productId"].Value;
            switch (productId)
            {
                case 1234:
                    member.ReturnValue = 45m;
                    break;
                case 2345:
                    member.ReturnValue = 15m;
                    break;
                default:
                    throw new ArgumentOutOfRangeException(
                        "productId");
            }
        }
        else
        {
            throw new InvalidOperationException("Unexpected member");
        }
    });
    ...
}

You see a repeating pattern … Very good, this calls for automation!

Automatic Mocks

With Automatic Mocks the approach is completely different. Instead of creating class instances manually, a framework will instantiate objects automatically at runtime.

For example using Rhino Mocks the code to mock an object implementing a certain interface looks like:

public void SaveOrderAndVerifyExpectations()
{
    MockRepository mocks = new MockRepository();
    IShopDataAccess dataAccess = mocks.CreateMock<IShopDataAccess>();

    ...
    // Start replay of recorded expectations
    mocks.ReplayAll();

    ...

    mocks.VerifyAll();
}

We have two modes: first the recording mode where expected results are defined and secondly a replay mode where the client accesses the mock objects.

Summary

Dummy
The simplest, most primitive type of test double. Dummies contain no implementation and are mostly used when required as parameter values, but not otherwise utilized. Nulls can be considered dummies, but real dummies are derivations of interfaces or base classes without any implementation at all.
Stub
A step up from dummies, stubs are minimal implementations of interfaces or base classes. Methods returning void will typically contain no implementation at all, while methods returning values will typically return hard-coded values.
Spy
A test spy is similar to a stub, but besides giving clients an instance on which to invoke members, a spy will also record which members were invoked so that unit tests can verify that members were invoked as expected.
Fake
A fake contains more complex implementations, typically handling interactions between different members of the type it’s inheriting. While not a complete production implementation, a fake may resemble a production implementation, albeit with some shortcuts.
Mock
A mock is dynamically created by a mock library (the others are typically produced by a test developer using code). The test developer never sees the actual code implementing the interface or base class, but can configure the mock to provide return values, expect particular members to be invoked, and so on. Depending on its configuration, a mock can behave like a dummy, a stub, or a spy.
Share this postSave this post