Tuesday, September 25, 2012

C# - Security - Cryptographic Agility

When developing any software it is really important to try and make your software as flexible as possible - loosely coupled designs with highly configurable components results in a much more sustainable and less fragile application.  Of particular concern in modern software is security; the most secure algorithms used in today's software are not the most secure algorithms in tomorrow's software.  In an effort to reduce hardcoding the cryptographic algorithms utilized within an application should be configurable leading to a concept known as Cryptographic Agility.  In the .Net world this is accomplished using the machine.config file stored within the .Net installation.  There is a great article that discusses how this is implemented and how to use it here, so I will not rehash it in this post.  There is no doubt that this is the preferred mechanism for implementing cryptographic agility in windows .Net applications as the machine.config file is managed by the administrators for the machine and are not generally accessible to all users on the machine (thus preventing just anyone from changing the algorithm to a less secure algorithm).  However, not all all deployment scenarios are necessarily able to accommodate these changes (maybe b/c it is a shared hosting site).  Thus, in this post I want to provide one alternative that allows you to take advantage of the machine.config file, but still offer an alternative for those times when the machine.config file is out of your control (or for those rare use cases where you need to override the machine.config).

One option is to use the application's properties to define the default algorithms if that machine.config file does not contain them. One possible scenario, and the one I will use here, is that all of your base crypto files/utils can extend from a base class that uses a static constructor to ensure that either the machine.config values exist OR that they are added to the CryptoConfig configuration from a property file.  There are other ways to initialize the CryptoConfig, of course, but this one is easy and works well.  However, it is important to note, that if an exception is thrown within the static constructor, that the application will NOT terminate and the class file will be left in an unusable state, so please make sure you code for this.  Some might consider this a bad decision (to use this static constructor), but I think it depends on your situation - in my case, if this fails that application can't be used, thus I check for this and fail out gracefully.

Now on to the example.  First create a base class from which your others can extend:

public abstract class Cryptography
{
     static Cryptography()
     {
     }
}

Before we fill in the static constructor, let's add a couple methods that we will be using within the constructor.  The first method will be the one used to register with CryptoConfig the algorithm defined in the properties file.  This will be used when the machine.config file is missing the mapping or when there is a desire to override it (more on this option shortly).

private static void SetAlgorithm(
  string name, string cryptoType)
{
 CryptoConfig config = new CryptoConfig();
 Type type = Type.GetType(cryptoType);
 CryptoConfig.AddAlgorithm(type, name);
}

The next method is the main method to check if the value is in the machine.config file, it it is not (the call to CreateFromName will return null), then it will call SetAlgorithm to set the type based on what is in the configuration file.  You must ensure there is a value in the configuration file as this class doesn't handle the situation where it is not (or add your own defaults to this class).

private static void SetConfiguration(
 string name, string type)
{
 object algorithm = CryptoConfig.CreateFromName(type);
 if (algorithm == null)
 {
  SetAlgorithm(name, type);
 }
}

Finally, back to the static constructor.  In order to allow overrides, we use a property to indicate that we should use the local settings rather than machine.config values.  In order to reduce code, I am using an action delegate to define that the method "SetAlgorithm" should be used when the UseLocalSettings property is set to true; thus, when this property is true, even if the algorithm is configured in machine.config, the local setting will be used instead.

static Cryptography()
{
 Action action = SetConfiguration;
 if(Properties.Settings.Default.UseLocalSettings)
 {
  action = SetAlgorithm;
 }
 action("Hash256", Properties.Settings.Default.Hash256);
 action("Hash512", Properties.Settings.Default.Hash512);
 action("Symmetric", Properties.Settings.Default.Symmetric);
 action("Asymmetric", Properties.Settings.Default.Asymmetric);
}

Edit: Thanks to a post from a google+ follower (Chris Eargle) I realized there was one omission (the generics on my Action) and a more elegant way to set the action method (ternary expression).

Action<string, string> action = 
     Properties.Settings.Default.UseLocalSettings ? 
           SetAlgorithm : SetConfiguration;

Finally, you just need to set these properties in your app.config file.  Each of the hash algorithms are strings and the UseLocalSettings property is a bool.  Example settings for the algorithm's values are as follows (for .Net 4.0):

Hash256=System.Security.Cryptography.SHA256CryptoServiceProvider, 
 System.Core, Version=4.0.0.0, Culture=neutral, 
 PublicKeyToken=b77a5c561934e089
Hash512=System.Security.Cryptography.SHA512CryptoServiceProvider, 
 System.Core, Version=4.0.0.0, Culture=neutral, 
 PublicKeyToken=b77a5c561934e089
Symmetric=System.Security.Cryptography.AesCryptoServiceProvider, 
 System.Core, Version=4.0.0.0, Culture=neutral, 
 PublicKeyToken=b77a5c561934e089
Asymmetric=System.Security.Cryptography.RSACryptoServiceProvider, 
 mscorlib, Version=4.0.0.0, Culture=neutral, 
 PublicKeyToken=b77a5c561934e089

I hope someone finds this useful... Feel free to comment if you have suggestions on how this can be improved or if you have questions about the content.

Thursday, September 20, 2012

C# - LINQ on dates

I recently had a need to get all the days in a month that were on a Monday (so for 9/2012 - the days are 3, 10, 17, 24).  Still being new to C#, LINQ was not my first thought... hell, it wasn't even one of my thoughts. I did a little googling to see if any of the current APIs did this already (I figured there was no reason to re-invent the wheel, right).  While I didn't find any APIs, I did find some ideas.  I found some similar examples using LINQ... so, I started playing around with them and this is what I ended up with.

The first part required an iteration of the days in the given month... for this, I used something else that I learned (and is no less cool) - the yield operator.  This is not something we have in the java world and I would really love to have it!
private static IEnumerable EnumerateDaysInRange(
                                   DateTime start, DateTime end)
{
    for (var day = start.Date; day <= end; day = day.AddDays(1))
 yield return day;
}
With this enumeration, I can now build a "from" component in a LINQ satement.
public static List DetermineDaysWeekly(
     Payee payee, 
     DayOfWeek dayOfWeek, 
     int month, 
     int year)
{
    DateTime firstDayOfMonth = new DateTime(year, month, 1);
    DateTime lastDayOfMonth = new DateTime(year, month, 
        DateTime.DaysInMonth(year, month));
    IEnumerable dates = 
     from date in 
            EnumerateDaysInRange(firstDayOfMonth, lastDayOfMonth)
   where (date.DayOfWeek == dayOfWeek)
   select date.Day;
    return dates.ToList();
}
All I am doing here is setting the date for the first day of the month and the last day of the month to pass to the previous function I built above (EnumerateDaysInRange).  The where clause simply checks if the day of the week during that iteration is the one we want and if it is (the select) captures the Day property on the date.  The days are all added to the IEnumerable object, which I convert to a list in my return statement.

Pretty simple really.  Now that I know more about LINQ, I will be sure to look for more places where this could be useful.  In this particular use case, I wasn't too worried about performance, but if I were, I would really need to take some time to research the performance of LINQ.  If anyone has thoughts regarding performance, or anything else for that matter, feel free to leave a comment.

Saturday, September 15, 2012

C# - Dynamic Factory for Commands

Factories are a useful and important mechanism in programming.  I have written many of them in Java and recently created one for Commands in C#.  There are many ways that a factory can work to provide you with implementations you request, but the ideal one handles it dynamically.  Once a factory is built, you really shouldn't have to manually add the implementations to a map... this is error prone and harder to maintain.  Ideally, you would just be able to add a new class, recompile, and run.  Even better, if done properly, this can be done by simply adding the class to a folder and it is automatically picked up.  For this post, I have thrown together a very simplified example of a factory that automatically loads the classes at runtime and are obtainable through a command name.  This example serves as the basis for a command line interpreter where the command passed in is used to lookup the implementation.

To start with, let's create an interface for Commands. For this example, I am using a base namespace of BlogSandox.
namespace BlogSandbox.command
{
    public interface ICommand
    {
        string CommandName { get; }
        string Execute(string input);
    }
}
All Commands will implement this interface and provide a command name (this is used to map the command to its instance).  To simplify all implementations, we will provide an abstract base class.
namespace BlogSandbox.command
{
    public abstract class BaseCommand : ICommand
    {
        private readonly string _commandName;

        protected BaseCommand(string commandName)
        {
            this._commandName = commandName;
        }

        public string CommandName
        {
            get { return _commandName; }
        }

        public abstract string Execute(string input);
    }
}
Now let's create a couple example Commands. Admittedly, these are pretty useless, but should help get the point across.
namespace BlogSandbox.command
{
    class EchoCommand : BaseCommand
    {        
        public const string NAME = "EchoCommand";
        public EchoCommand()
            : base(NAME)
        {
        }

        public override string Execute(string input)
        {
            return input;
        }
    }
}

namespace BlogSandbox.command
{
    class GreetCommand : BaseCommand
    {
        public const string NAME = "GreetCommand";
        public GreetCommand()
            : base(NAME)
        {
        }

        public override string Execute(string input)
        {
            return "Hello " + input + "!";
        }
    }
}
Now for the command factory.  This factory is going to register each instance using the "CommandName" provided by the implementing classes.  While this example doesn't have a "collision" detection (e.g. when 2 commands have the same name), it is not a bad idea to add one if you will be dealing with a lot of commands and especially if you will be making them pluggable.

namespace BlogSandbox.command
{
    public class CommandFactory
    {
        private readonly Dictionary _commandImplementations;
        private static volatile CommandFactory _commandFactoryInstance;
        private static object _syncRoot = new object();

        private CommandFactory()
        {
            _commandImplementations = new Dictionary();
            Initialize();
        }

        public static CommandFactory Instance
        {
            get
            {
                if (_commandFactoryInstance == null)
                {
                    lock (_syncRoot)
                    {
                        _commandFactoryInstance = new CommandFactory();
                    }
                }
                return _commandFactoryInstance;
            }
        }

        public ICommand GetCommand(string commandName)
        {
            return _commandImplementations[commandName.ToLower()];
        }

        private void Initialize()
        {
            // 1. get assembly
            Assembly asm = Assembly.GetCallingAssembly();

            // 2. get the list of all types in this assembly and iterate
            foreach (Type type in asm.GetTypes())
            {
                // we want the non-abstract implementations of ICommand
                if (type.IsClass && !type.IsAbstract)
                {
                    Type iCommand = 
                        type.GetInterface(
                          "BlogSandbox.command.ICommand");
                    if (iCommand != null)
                    {
                        // create an instance
                        object inst = 
                            asm.CreateInstance(type.FullName, true, 
                             BindingFlags.CreateInstance, null, null,
                             null, null);
                        if (inst != null)
                        {
                            ICommand commandInst = (ICommand)inst;
                            // make it case insensitive
                            string key = 
                                commandInst.CommandName.ToLower();
                            _commandImplementations.Add(
                                key, commandInst);
                        }
                        else
                        {
                            string errMsg =
                                "CommandFactory.Initialize(): Unable " +
                                "to properly initialize " +
                                "CommandFactory - there was a " +
                                "problem instantiating the class " +
                                type.FullName;
                            throw new Exception(errMsg);
                        }
                    }
                }
            }
        }
    }
}
The main thing to catch here is the use of the "Assembly" to find the classes and then load the ones that are of the appropriate type (e.g. non-abstract class that implements our command interface ICommand). To see this working, here is a simple main that you can add for a Console Application.  The sleep at the bottom keeps the window open long enough to see the results... of course, you could use a logger or other application type that doesn't close up at completion.
namespace BlogSandbox
{
    class Program
    {
        static void Main(string[] args)
        {
            CommandFactory factory = CommandFactory.Instance;
            Console.WriteLine("Echo Command: " + 
                factory.GetCommand(EchoCommand.NAME).
                    Execute("Repeat me"));
            Console.WriteLine("Greet Command: " + 
                factory.GetCommand(GreetCommand.NAME).
                    Execute("Paul"));
            Thread.Sleep(20000);
        }
    }
}
These commands are clearly very simplified, but I hope that you can see how this can be applied in your own use case.  In a full implementation that I wrote for work, the BaseCommand method had protected methods for performing validations on the commands, returned a CommandResponse object where errors could be added in a list or a successful response could be provided (such as returning a result of the action). Additionally, for building my commands I used a fantastic command line parser library.  I highly recommend this library as it really simplified taking in command arguments.

This simplified example really only touches on the factory for commands, but doesn't really discuss a good way to implement the commands, nor how to parse a command line.  In a future post, I will explore the Command Line Parser Library I used and try to build from this example so that you can see more of the whole picture.  I hope this helps someone out there!  As always, feel free to use my code - while not necessary, attribution in the form of a link back to this post is always appreciated!

Thursday, September 13, 2012

C# coolness - extension methods

This is a feature that I fell in love with in Groovy - the ability to add functionality to existing classes. This dynamic capability can really reduce your code footprint significantly with only moderate complexity!  I recently had a use case where I wanted to be able to split a string based on spaces (this was for command line parsing).  With a little assist from some code found on StackOverflow and this functionality, I had a quick and useful extension I could use in parsing out the command line.  This could still use a little work, but is pretty functional for most basic cases.

First - attribution.  The split code in this post was inspired by this response to a question on StackOverflow.

In order to create extension methods, you have to define your class as a public static class.  Extension methods are static methods and the first parameter is the type you are extending - here is the syntax: "this typeExtending varName".  This first snippet sets up a new Split method that takes in a delegate for how it should act on each character.

public static IEnumerable<string> Split(this string text, 
    Func<char, bool> internalFunction)
{
    int next = 0;
    for (int chr = 0; chr < text.Length; chr++)
    {
        if (internalFunction(text[chr]))
        {
            yield return text.Substring(next, 
                      chr - next).CleanString();
            next = chr + 1;
        }
        // process the last char differently b/c IF it 
        // is a quote, it will get left out (since 
        // internalFunction will return false since it 
        // never reaches the split character - unless a 
        // trailing space is added).
        else if (chr == text.Length - 1)
        {
            yield return text.Substring(next).CleanString();
        }
    }
}

Here is the implementation for the CleanString method (used in the above snippet).  Notice that this is also an extension method:

public static string CleanString(this string str)
{
    string returnStr = str;
    if (!String.IsNullOrEmpty(str))
    {
        returnStr = returnStr.Trim();
        returnStr = returnStr.TrimMatchingQuotes();
    }
    return returnStr;
}

Here is the implementation for the TrimMatchingQuotes (used in the above snippet).  This is again an extension method:


public static string TrimMatchingQuotes(this string input)
{
    // strings less than 2 chars don't have matching quotes 
    if ((input.Length >= 2) &&
        (input[0] == QUOTE) && 
        (input[input.Length - 1] == QUOTE))
    {
        return input.Substring(1, input.Length - 2);
    }
    return input;
}


Now for the final piece of goodness!  For splitting command lines that honor quotes (e.g. executable -t "some text") - please note, this does not work with quotes inside your quotes - I leave that to you if you need it!


public static IEnumerable 
    SplitStringHonorQuotes(this string str, char splitChar)
{
    bool inQuotes = false;
    return str.Split(character =>
                {
                    if (character == QUOTE)
                    {
                        // if we're in quotes, now we aren't
                        inQuotes = !inQuotes;
                    }
                    // don't split if inside a quoted section
                    return !inQuotes && character == splitChar;
                });
}


That's it, now you have some extension methods to help split your command line.  Drop all that code in a class like this:
 

using System;
using System.Collections.Generic;

namespace ProjectNamespace
{
    public static class StringUtils
    {
        // This constant is used in above code
        private const char QUOTE = '\"';
        // add above code here...
    }
}

Now, to use it:

// import your StringUtils class with extension methods
using ProjectNamespace;
...
string[] cmdArgs = 
   "-C command -t \"some text\"".SplitStringHonorQuotes(' ').ToArray();


I hope you found this post useful! Feel free to use this code as you wish... if you need a license, you can use the Apache license.  A link back to this post, while not required, would be appreciated.

Finally, I welcome constructive criticism on how this can be improved.  I am new to the .Net world, so I am still learning what C# has to offer.

Tuesday, September 11, 2012

9/11

It is only fitting that my first (well second if you include my goals post earlier) real blog post be about 9/11 since it is, after all, the 11th anniversary of one of the most tragic events in US history (at least in my lifetime).  That day is, for many of us, burned into our memories - most of us remember where we were and what we were doing.  For me, I was in my 2nd year of graduate school (back when I thought I wanted a PhD in Biology).  I was working in the lab that morning when someone charged in and said a plane had just flown into one of the towers (as it happens, it was the north tower).  There was no TV in the lab and the radio left a lot to be desired so we attempted to tune in on my computer.  This was the early days of streaming news and getting a connection was very difficult, maintaining it was even harder.  Nonetheless, we could see most of the events in all its gory details as it went down.  It is a day that I will never forget... the pain, the anger, and the fear that someone could attack us on our own land - this is not something Americans were used to.  That day changed a lot of lives... it was a horrific event that would change the direction of this country and help propel us into economic turmoil.

Since that fateful day there have been more than 4000 military deaths (this number is pulled from a quick google search and may not be all that accurate).  Additionally, so many of the first responders to the towers have died from complications due the toxic air they inhaled that day.  So much has been lost, but I am astounded by our resilience... our ability to keep moving forward.  That day the terrorist won a battle, but we have and will continue to win the war.  Freedom is not free and I am humbled by all the men and women that are willing to pay the ultimate price so that I may have the right to express my feelings on a stupid little blog.  So, today, I express my gratitude to all of the soldiers in the military, the fireman, and the police for laying it all on the line for us.

In remembrance to the fallen... we will never forget.

To those that would harm us - we will not fall and you will not succeed.

Goals...

Periodically, I get inspired to start blogging... Well, this is my attempt at doing just that.  For my first post I thought I would start with something simple - my goals.  As a lead software engineer I spend a lot of my time in meetings; this is far from my ideal, but it pays the bills.  One of the more enjoyable aspects of my jobs is that I get to do a lot of architecture work... these days, my focus is on software security.  My goal for this blog will to be write about things that I find interesting, challenging, and just generally useful.  Over the last couple of months I have been working on software that is/will be deployed on government systems and have had a few challenges for security.  Additionally, while I have spent most of my career working with Java, lately I have been doing most of my work in C#.  These challenges have certainly provided me with a few good topics to discuss.  This will not be a daily entry blog... I just don't have the time, but I do hope to provide weekly posts.  I hope that my readers find my content useful! 

Oh yeah, one last warning... my hobby is lifting, running, and nutrition - don't be surprised if I throw in a post or two on those topics :-)

Followers