Making the X509Store more Friendly

When you need to grab a certificate out of a Windows Certificate Store, you can use a class called X509Store.  It's very simple to use:

X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

store.Open(OpenFlags.ReadOnly);

X509Certificate2Collection myCerts = store.Certificates.Find(X509FindType.FindByThumbprint, "...", false);

store.Close();

However, I don't like this open/close mechanism.  It reminds me too much of Dispose(), except I can't use a using statement.  There are lots of arguments around whether a using statement is a good way of doing things and I'm in the camp of yes, it is.  When they are used properly they make code a lot more logical.  It creates a scope for an object explicitly.  I want to do something like this:

using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser, OpenFlags.ReadOnly))
{
    X509Certificate2Collection myCerts = store.Certificates.Find(X509FindType.FindByThumbprint, "...", false);
}

The simple solution would be to subclass this, implement IDisposable, and overwrite some of the internals.  The problem though is that someone on the .NET team thought it would be wise to seal the class.  Crap.  Okay, lets create a new class:

public class X509Store2 : IDisposable
{
    private X509Store store;

    public X509Store2(IntPtr storeHandle, OpenFlags flags)
    {
        store = new X509Store(storeHandle);
        store.Open(flags);
    }

    public X509Store2(StoreLocation storeLocation, OpenFlags flags)
    {
        store = new X509Store(storeLocation);
        store.Open(flags);
    }

    public X509Store2(StoreName storeName, OpenFlags flags)
    {
        store = new X509Store(storeName);
        store.Open(flags);
    }

    public X509Store2(string storeName, OpenFlags flags)
    {
        store = new X509Store(storeName);
        store.Open(flags);
    }

    public X509Store2(StoreName storeName, StoreLocation storeLocation, OpenFlags flags)
    {
        store = new X509Store(storeName, storeLocation);
        store.Open(flags);
    }

    public X509Store2(string storeName, StoreLocation storeLocation, OpenFlags flags)
    {
        store = new X509Store(storeName, storeLocation);
        store.Open(flags);
    }

    public X509Certificate2Collection Certificates { get { return store.Certificates; } }

    public StoreLocation Location { get { return store.Location; } }

    public string Name { get { return store.Name; } }

    public IntPtr StoreHandle { get { return store.StoreHandle; } }

    public void Add(X509Certificate2 certificate)
    {
        store.Add(certificate);
    }

    public void AddRange(X509Certificate2Collection certificates)
    {
        store.AddRange(certificates);
    }

    private void Close()
    {
        store.Close();
    }

    private void Open(OpenFlags flags)
    {
        store.Open(flags);
    }

    public void Remove(X509Certificate2 certificate)
    {
        store.Remove(certificate);
    }
    public void RemoveRange(X509Certificate2Collection certificates)
    {
        store.RemoveRange(certificates);
    }

    public void Dispose()
    {
        this.Close();
    }
}

At this point I've copied all the public members of the X509Store class and called their counterparts in the store.  I've also set Open() and Close() to private so they can't be called.  In theory I could just remove them, but I didn't.

Enjoy!

The Basics of Building a Security Token Service

Last week at TechDays in Toronto I ran into a fellow I worked with while I was at Woodbine.  He works with a consulting firm Woodbine uses, and he caught my session on Windows Identity Foundation.  His thoughts were (essentially—paraphrased) that the principle of Claims Authentication was sound and a good idea, however implementing it requires a major investment.  Yes.  Absolutely.  You will essentially be adding a new tier to the application.  Hmm.  I’m not sure if I can get away with that analogy.  It will certainly feel like you are adding a new tier anyway.

What strikes me as the main investment is the Security Token Service.  When you break it down, there are a lot of moving parts in an STS.  In a previous post I asked what it would take to create something similar to ADFS 2.  I said it would be fairly straightforward, and broke down the parts as well as what would be required of them.  I listed:

  • Token Services
  • A Windows Authentication end-point
  • An Attribute store-property-to-claim mapper (maps any LDAP properties to any claim types)
  • An application management tool (MMC snap-in and PowerShell cmdlets)
  • Proxy Services (Allows requests to pass NAT’ed zones)

These aren’t all that hard to develop.  With the exception of the proxy services and token service itself, there’s a good chance we have created something similar to each one if user authentication is part of an application.  We have the authentication endpoint: a login form to do SQL Authentication, or the Windows Authentication Provider for ASP.NET.  We have the attribute store and something like a claims mapper: Active Directory, SQL databases, etc.  We even have an application management tool: anything you used to manage users in the first place.  This certainly doesn’t get us all the way there, but they are good starting points.

Going back to my first point, the STS is probably the biggest investment.  However, it’s kind of trivial to create an STS using WIF.  I say that with a big warning though: an STS is a security system.  Securing such a system is NOT trivial.  Writing your own STS probably isn’t the best way to approach this.  You would probably be better off to use an STS like ADFS.  With that being said it’s good to know what goes into building an STS, and if you really do have the proper resources to develop one, as well as do proper security testing (you probably wouldn’t be reading this article on how to do it in that case…), go for it.

For the sake of simplicity I’ll be going through the Fabrikam Shipping demo code since they did a great job of creating a simple STS.  The fun bits are in the Fabrikam.IPSts project under the Identity folder.  The files we want to look at are CustomSecurityTokenService.cs, CustomSecurityTokenServiceConfiguration.cs, and the default.aspx code file.  I’m not sure I like the term “configuration”, as the way this is built strikes me as factory-ish.

image

The process is pretty simple.  A request is made to default.aspx which passes the request to FederatedPassiveSecurityTokenServiceOperations.ProcessRequest() as well as a newly instantiated CustomSecurityTokenService object by calling CustomSecurityTokenServiceConfiguration.Current.CreateSecurityTokenService().

The configuration class contains configuration data for the STS (hence the name) like the signing certificate, but it also instantiates an instance of the STS using the configuration.  The code for is simple:

namespace Microsoft.Samples.DPE.Fabrikam.IPSts
{
    using Microsoft.IdentityModel.Configuration;
    using Microsoft.IdentityModel.SecurityTokenService;

    internal class CustomSecurityTokenServiceConfiguration
: SecurityTokenServiceConfiguration
    {
        private static CustomSecurityTokenServiceConfiguration current;

        private CustomSecurityTokenServiceConfiguration()
        {
            this.SecurityTokenService = typeof(CustomSecurityTokenService);
            this.SigningCredentials =
new X509SigningCredentials(this.ServiceCertificate);
            this.TokenIssuerName = "https://ipsts.fabrikam.com/";
        }

        public static CustomSecurityTokenServiceConfiguration Current
        {
            get
            {
                if (current == null)
                {
                    current = new CustomSecurityTokenServiceConfiguration();
                }

                return current;
            }
        }
    }
}

It has a base type of SecurityTokenServiceConfiguration and all it does is set the custom type for the new STS, the certificate used for signing, and the issuer name.  It then lets the base class handle the rest.  Then there is the STS itself.  It’s dead simple.  The custom class has a base type of SecurityTokenService and overrides a couple methods.  The important method it overrides is GetOutputClaimsIdentity():

protected override IClaimsIdentity GetOutputClaimsIdentity(
IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
{
    var inputIdentity = (IClaimsIdentity)principal.Identity;

    Claim name = inputIdentity.Claims.Single(claim =>
claim.ClaimType == ClaimTypes.Name);
    Claim email = new Claim(ClaimTypes.Email,
Membership.Provider.GetUser(name.Value, false).Email);
    string[] roles = Roles.Provider.GetRolesForUser(name.Value);

    var issuedIdentity = new ClaimsIdentity();
    issuedIdentity.Claims.Add(name);
    issuedIdentity.Claims.Add(email);

    foreach (var role in roles)
    {
        var roleClaim = new Claim(ClaimTypes.Role, role);
        issuedIdentity.Claims.Add(roleClaim);
    }

    return issuedIdentity;
}

It gets the authenticated user, grabs all the roles from the RolesProvider, and generates a bunch of claims then returns the identity.  Pretty simple.

At this point you’ve just moved the authentication and Roles stuff away from the application.  Nothing has really changed data-wise.  If you only cared about roles, name, and email you are done.  If you needed something more you could easily add in the logic to grab the values you needed. 

By no means is this production ready, but it is a good basis for how the STS creates claims.

Azure Blob Uploads

Earlier today I was talking with Cory Fowler about an issue he was having with an Azure blob upload.  Actually, he offered to help with one of my problems first before he asked me for my thoughts – he’s a real community guy.  Alas I wasn’t able to help him with his problem, but it got me thinking about how to handle basic Blob uploads. 

On the CommunityFTW project I had worked on a few months back I used Azure as the back end for media storage.  The basis was simple: upload media stuffs to a container of my choice.  The end result was this class:

    public sealed class BlobUploadManager
    {
        private static CloudBlobClient blobStorage;

        private static bool s_createdContainer = false;
        private static object s_blobLock = new Object();
        private string theContainer = "";

        public BlobUploadManager(string containerName)
        {
            if (string.IsNullOrEmpty(containerName))
                throw new ArgumentNullException("containerName");

            CreateOnceContainer(containerName);
        }

        public CloudBlobClient BlobClient { get; set; }

        public string CreateUploadContainer()
        {
            BlobContainerPermissions perm = new BlobContainerPermissions();
            var blobContainer = blobStorage.GetContainerReference(theContainer);
            perm.PublicAccess = BlobContainerPublicAccessType.Container;
            blobContainer.SetPermissions(perm);

            var sas = blobContainer.GetSharedAccessSignature(new SharedAccessPolicy()
            {
                Permissions = SharedAccessPermissions.Write,
                SharedAccessExpiryTime = DateTime.UtcNow + TimeSpan.FromMinutes(60)
            });

            return new UriBuilder(blobContainer.Uri) { Query = sas.TrimStart('?') }.Uri.AbsoluteUri;
        }

        private void CreateOnceContainer(string containerName)
        {
            this.theContainer = containerName;

            if (s_createdContainer)
                return;

            lock (s_blobLock)
            {
                var storageAccount = new CloudStorageAccount(
                                         new StorageCredentialsAccountAndKey(
                                             SettingsController.GetSettingValue("BlobAccountName"),
                                             SettingsController.GetSettingValue("BlobKey")),
                                         false);

                blobStorage = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer container = blobStorage.GetContainerReference(containerName);
                container.CreateIfNotExist();

                container.SetPermissions(
                    new BlobContainerPermissions()
                    {
                        PublicAccess = BlobContainerPublicAccessType.Container
                    });

                s_createdContainer = true;
            }
        }

        public string UploadBlob(Stream blobStream, string blobName)
        {
            if (blobStream == null)
                throw new ArgumentNullException("blobStream");

            if (string.IsNullOrEmpty(blobName))
                throw new ArgumentNullException("blobName");

            blobStorage.GetContainerReference(this.theContainer)
		       .GetBlobReference(blobName.ToLowerInvariant())
		       .UploadFromStream(blobStream);

            return blobName.ToLowerInvariant();
        }
    }

With any luck with might help someone trying to jump into Azure.

C# Dynamic Type Conversions

I’ve been looking at ways of parsing types and values from text without having to do switch/case statements or explicit casting.  So far, based on my understanding of statically typed languages, is that this is impossible with a statically typed language.

<Question> Is this really true?</Question>

Given my current knowledge, my way of bypassing this is to use the new dynamic type in .NET 4.  It allows me to implicitly assign an object without having to cast it.  It works by bypassing the type checking at compile time.

Here’s a fairly straightforward example:

static void Main(string[] args)
{
	Type boolType = Type.GetType("System.Boolean");
	Console.WriteLine(!parse("true", boolType));

	Type dateTimeType = Type.GetType("System.DateTime");

	DateTime date = parse("7/7/2010", dateTimeType);
	Console.WriteLine(date.AddDays(1));

	Console.ReadLine();
}

static dynamic parse(string value, Type t)
{
	return Convert.ChangeType(value, t);
}

Now, if I were to do something crazy and call

DateTime someDate = parse(“1234”, Type.GetType(“System.Int32”));

a RuntimeBinderException would be thrown because you cannot implicitly convert between an int and a DateTime.

It certainly makes things a little easier.

SQL Server 2008 R2 Launch Event &amp;ndash; Application Lifecycle Management

Unfortunately I will be unable to attend the ALM presentation later this afternoon, but luckily I was able to catch it in Montreal last week.

When I think of ALM, I think of the development lifecycle of an application – whether it be agile or waterfall or whatever floats your boat – that encompasses all parts of the process.  We’ve had tools over the years that help us manage each section or iteration of the process, but there was some obvious pieces missing.  What about the SQL?  Databases are essential to pretty much all applications that get developed nowadays, yet for a long time we didn’t have much in the way to help streamline and manage the processes of developing database pieces.

Enter ALM for SQL Server.  DBA’s are now given all the tools and resources developers have had for a while.  It’s now easier to manage Packaging and Deployment of Databases, better source control of SQL scripts, and something really cool: Database schema versioning.

I have a story: Sometime over the last couple years, a developer wrote a small little application that monitors changes to database schemas through triggers, and then sync’ed the changes with SVN.  This was pretty cool.  It allowed us to watch what changed when things went south.  Problem was, it wasn’t necessarily reliable, it relied on some internal pieces to be added to the database manually, and made finding changes through SVN tricky.

With ALM, versioning of databases happens before deployment.  Changes are stored in TFS, and its possible to rollback certain changes fairly easily.  Certain changes. :)

That’s pretty cool.

Bad User Interfaces are Insecure

The Best of Intentions

So you’ve built this application.  It’s a brilliant application.  It’s design is spectacular, the architecture is flawless, the coding is clean and coherent, and you even followed the SDL best practices and created a secure application.

There is one minor problem though.  The interface is terrible.  It’s not intuitive, and settings are poorly described in the options window.  A lot of people wouldn’t necessarily see this as a security issue, but more of an interaction bug -- blame the UX people and get on with your day.

Consider this (highly hyperbolic) options window though:

BadSecuritySettings

How intuitive is it?  Notsomuch, eh?  You have to really think about what it’s asking.  Worst of all, there is so much extraneous information there that is supposed to help you decide.

At first glance I’m going to check it.  I see “security” and “enable” in the text, and naturally assume it’s asking me if I want to make it run securely (lets say for the sake of argument it speaks the truth), because god knows I’m not going to read it all the way through the first time.

By the second round through I’ve already assumed I know what it’s asking, read it fully, get confused, and struggle with what it has to say.

A normal end user will not even get to this point.  They’ll check it, and click save without thinking, because of just that – they don’t want to have to think about it.

Now, consider this:

GoodSecuritySettings

Isn’t this more intuitive?  Isn’t it easier to look at?  But wait, does it do the same thing?  Absolutely.  It asks the user if they want to run a secure application.

The Path to Security Hell

When I first considered what I wanted to say on this topic, I asked myself “how can this really be classified as a security bug?”  After all, it’s the user’s fault for checking it right?

Well, no.  It’s our fault.  We developed it securely, we told them they needed it to be run securely, and we gave them the option to turn off security (again, hyperbole, but you get the point).  It’s okay to let them choose if they want to run an insecure application, but if we confuse them, if we make it difficult to understand what the heck is going on, they aren’t actually doing what they want and we therefore failed at making the application they wanted secure, secure.

It is our problem.

So what?

Most developers I know at the very least will make an attempt to write a secure application.  They check for buffer overflows, SQL Injection, Cross Site Scripting, blah blah blah.  Unfortunately some, myself included, tend to forget that the end users don’t necessarily know about security, nor care about it.  We do like most developers do.  We tell them what we know: “There has been a fatal exception at 0x123FF567!!one! The index was outside the bounds of the array.  We need to destroy the application threads and process.”

That sounds fairly familiar to most error messages we display to our end users.  Frankly, they don’t care about it.  They are just pissed the work they were doing was just lost.

The funny thing is, we really don’t notice this.  When I was building the first settings window above, I kept reading the text and thinking to myself, it makes perfect sense.  The reason for this is by virtue of the fact that what I wrote is my logic.  I wrote the logic, I wrote the text, I inherently understand what I wrote.  We do this all the time.  I do this all the time, and then I get a phone call from some user saying “wtf does this mean?”, aaaaaaand then I change it to something a little more friendly.  By the 4th or so iteration of this I usually get it right (or maybe they just get tired of calling?).

So what does this say about us? Well, I’m not sure. I think it’s saying we need to work on our user interface skills, and as an extension of that, we need to work on our soft skills – our interpersonal skills. Maybe. Just a thought.

My First CodePlex Project!

A few minutes ago I just finalized my first CodePlex project.  While working on the ever-mysterious Infrastructure 2010 project, I needed to integrate the Live Meeting API into an application we are using.  So I decided to stick it into it’s own assembly for reuse.

I also figured that since it’s a relatively simple project, and because for the life of me I couldn’t find a similar wrapper, I would open source it.  Maybe there is someone out there who can benefit from it.

The code is ugly, but it works.  I suspect I will continue development, and clean it up a little.  With that being said:

  • It needs documentation (obviously).
  • All the StringBuilder stuff should really be converted to XML objects
  • It need's cleaner exception handling
  • It needs API versioning support
  • It needs to implement more API functions

Otherwise it works like a charm.  Check it out!

Visual Studio Output Window Auto-Scrolling

Just a quick one here.

Have you ever been using the output window in Visual Studio, scrolled up, and then lost the auto-scroll functionality?  It’s really annoying when you have a thousand things coming out through the likes of Debug.Write, or even if it’s just a massive build.

To re-enable autoscrolling, while in the output window just hit CTRL+END.

Kinda wished I knew that a year ago…

A Thought on Windows Mobile 7

The other day while I was sitting in the airport in Washington, D.C., I had a random thought.  When the ZuneHD first hit the shelves people were talking about how Mobile 7 might borrow the look and feel.  It’s sleek, easy to use/easy to understand, and is very simple.  So I started thinking about what such an interface might look like.  This is something I did quickly.  Nothing was provided by Microsoft.  Nobody has said anything about Mobile 7 design (at least, not at that point, but nobody cared anyway).  This is simply something I thought the interface might look like.

homeScreen

Some things to notice are the list-like menu’s, and the bing search at the bottom.  Blah-blah-blah anti-trust, the point is search is easily accessible, not necessarily just to Microsoft’s own search engine.  It could be Google’s search too.  Also, there is the location-specific information at the top showing the current weather.  Also mimicking the Windows 7 interface is the idea of pinning things to the home screen such as the Internet Explorer application.

There are some things that should probably change.  It feels a little cluttered at the bottom showing current messages and the appointments color is iffy.  There may not be any need for the middle separation either.

Just a thought…

Deleting Temporary Internet Files from the Command Line

A quicky but a goody.  Sometimes you just need a quick way to delete temp files from IE.  In most cases for me its when I’m writing a webapp, so I’ve stuck this in the build properties:

RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 4351

It doesn’t require elevated permissions, and has been tested on Vista and Windows 7.  Each command deletes the different types of data: temp files, stored form info, cookies etc.  Enjoy.