Encrypting (Hashing) Passwords for your Website

In my previous blog entry which explains how to implement a custom MembershipProvider on an ASP.Net MVC web site, I mentioned the BCrypt library in passing. Today I’d like to dig into the library a little more and show you how and why you should consider using it.

Before we get into that though, what is what is ‘hashing’ and how is it different to ‘encryption’?

Encryption is part of a two way process in which data is encoded, but must be decryptable afterwards. For password storage, this decryption step is unnecessary and is actually a security vulnerability if someone gets hold of your keys.

In contrast, hashing is a one way transformation that is very hard to reverse. So to store passwords, a site would simply hash them before saving them to a database. Then when a user logs in, the password they supply is also hashed and compared to the hashed value in the database. If they typed in the same password the hashes will match and the authentication passes.

The advantage of this, is that the web site doesn’t need to decrypt a password at any point. All it ever does is hash them which is great for security.

There are various hashing algorithms out there, and many of them are wonderfully optimised and very fast. A typical example is SHA. An optimal hasher sounds great doesn’t it?

… well it isn’t. In fact it’s a weakness with the power of modern cpus and cloud computing resources. It means that its very possible and remarkably cheap to brute force SHA with a dictionary attack, simply because it is so fast.

This is where BCrypt comes in. It is intentionally slow, so should someone try to brute force it, its simply not viable. Whereas a hacker can generate 100s of millions of SHA hashes a second, they can’t with BCrypt, and as technology marches on, you can just increase the work factor on BCrypt to keep ahead of processors.

There are a few BCrypt.Net implementations floating around, and the one I’ve used I pulled down with nuget. To use it is as simple as:

private static readonly int BCRYPT_WORK_FACTOR = 10;
string hashedPassword = BCrypt.Net.BCrypt.HashPassword(account.HashedPassword, BCRYPT_WORK_FACTOR);
bool matched = BCrypt.Net.BCrypt.Verify(password, match.HashedPassword))

Every increment in work factor doubles the type the hash takes. Some of the .net implemtations struggle to get past 31 due to a bug, but you shouldn’t need a value anything like that high for a few years at least!

ASP.Net MVC 3 Custom Membership Provider with Repository Injection

In most serious ASP.NET MVC, or even legacy ASP.Net web sites, you are unlikely to want to use the default membership provider of ASP.Net. Its dependency on SQLServer and unhealthy predilection for littering databases with hundreds tables, just to support features you don’t care about, make it distinctly unattractive.

What we really want is to integrate our web site’s security with the project’s schema and bind directly to a table or repository encapsulating the users model for the site. The way to do this is through the implementation of a custom MembershipProvider.

This may seem a little daunting, but in practise is fairly simple. In fact, all we need do is override a pair of methods, on a couple of abstract classes, and all authentication and role checking will be routed to our code. Even better, by leveraging the well-tested and robust ASP.NET security facilities, we can still utilise the convenience and security of ASP.Net’s attribute based security to protect your controllers and controller methods. If you aren’t familiar with these, it’s as simple as attaching an Authorise tag, and optionally specifying a role the user must have to gain access e.g.

public class MemberController : Controller
{
	IAccountRepository repo;

	public MemberController(IAccountRepository accountRepository)
	{
		repo = accountRepository;
	}

	[Authorize]
	public ActionResult Index()
	{
...
	}

	[Authorize(Roles = "Admin")]
	public ActionResult Delete(int accountId)
	{
...
	}
}

Just being authorised means the user has been authenticated i.e. logged in. The role is supplementary to this and allows you finer grained access control. Easy huh?

So, firstly authentication. To take control of this, we have to create a class derived from the abstract class MembershipProvider.

Unfortunately, being a hangover from old-school ASP.net, wiring this in is a little more clumsy than one might expect. It predates the pluggable design pattern applied throughout the MVC platform. The upshot being, that if you want to use the repository pattern with it, you can’t pass a repository into the constructor as ASP.Net instantiates the class for you, and only knows how to do this through a default constructor.

One way to work around this is to make your repository a property on the class and update it after the framework has constructed it. In this example I’m going to use ninject as my DI framework, but you could use a different one, or in fact just set the property without using DI at all.

First lets start with an example membership provider. I’ve only bothered to override ValidateUser() as the other methods aren’t required to leverage ASP.NET’s integrated security features.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using Ninject;

namespace MyProj.Web.Infrastructure
{
	public class AccountMembershipProvider : MembershipProvider
	{
		[Inject]
		public IAccountRepository AccountRepository { get; set; }

		public override string ApplicationName
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

... lots of unimplemented overrides...

		public override void UpdateUser(MembershipUser user)
		{
			throw new NotImplementedException();
		}

		public override bool ValidateUser(string username, string password)
		{
			return AccountRepository.IsValidLogin(username, password);
		}
	}
}

You’ll notice there is an AccountRepository being used here to validate the user login. This is where your custom authorisation logic goes – as such I’m not going to provide an implementation here as it will depend on the specifics of your site.

Next, we need to ensure that the AccountRepository is injected into our MembershipProvider, and the place to do this is Application_Start() in Gloabl.asax.

	internal class MyNinjectModules : NinjectModule
	{
		public override void Load()
		{
			Bind<IAccountRepository>()
				.To<AccountRepository>();
		}
	}

	public class MvcApplication : System.Web.HttpApplication
	{
		private IKernel _kernel = new StandardKernel(new MyNinjectModules());

...code deleted....

		protected void Application_Start()
		{
			AreaRegistration.RegisterAllAreas();

			RegisterGlobalFilters(GlobalFilters.Filters);
			RegisterRoutes(RouteTable.Routes);

			// Inject account repository into our custom membership provider.
			_kernel.Inject(Membership.Provider);
		}
	}

You’ll notice that I’m grabbing the framework instantiated instance of our membership provider, and using ninject to set the repository property on our custom membership provider.

I’m also setting up a ninject controller factory which is a great class when you want to inject repositories into your controller’s constructors. This is based on code found in one of the best programming books I’ve ever read Pro ASP.NET MVC 2 Framework by Steven Sanderson. This book covers so much more than ASP.NET MVC, it teaches you how to design and build applications for testability, and is the most digestable explanation of modern test driven design I’ve ever come across. It’s worth a read even if you aren’t an MVC programmer! n.b. I believe a revised MVC3 edition is to be released shortly.

public class NinjectControllerFactory : DefaultControllerFactory
	{
		private IKernel _kernel;

		public NinjectControllerFactory(IKernel kernel)
		{
			_kernel = kernel;
		}

		protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
		{
			if (controllerType == null)
				return null;
		 
			return (IController)_kernel.Get(controllerType);
		}
	}

Now… what if we want to create a custom role provider too? Well that’s easy. Here is an exampe RoleProvider:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using Ninject;

namespace MyProj.Web.Infrastructure
{
	public class AccountRoleProvider : RoleProvider
	{
		[Inject]
		public IAccountRepository AccountRepository { get; set; }

		public override void AddUsersToRoles(string[] usernames, string[] roleNames)
		{
			throw new NotImplementedException();
		}

... lots of unimplemented overrides...

		public override string[] GetRolesForUser(string id)
		{
			return AccountRepository.GetRoles(id);
		}

... lots of unimplemented overrides...

		public override bool RoleExists(string roleName)
		{
			throw new NotImplementedException();
		}
	}
}

Again, you really don’t need to override much of the RoleProvider abstract class, simply implementing GetRolesForUser() and ensuring it returns a string array of the given users roles will suffice.

To inject the membership provider juat change the previous code version of Application_Start() to:

	public class MvcApplication : System.Web.HttpApplication
	{
		private IKernel _kernel = new StandardKernel(new MyNinjectModules());

...code deleted....

		protected void Application_Start()
		{
			AreaRegistration.RegisterAllAreas();

			RegisterGlobalFilters(GlobalFilters.Filters);
			RegisterRoutes(RouteTable.Routes);

			// Inject account repository into our custom membership & role providers.
			_kernel.Inject(Membership.Provider);
			_kernel.Inject(Roles.Provider);
		}
	}

Finally we need to register our providers in web.config:

<configuration>
...
  <system.web>
...
    <membership defaultProvider="AccountMembershipProvider">
      <providers>
        <clear/>
        <add name="AccountMembershipProvider"
             type="MyProj.Web.Infrastructure.AccountMembershipProvider" />
      </providers>
    </membership>

    <roleManager enabled="true" defaultProvider="AccountRoleProvider">
      <providers>
        <clear/>
        <add name="AccountRoleProvider"
             type="MyProj.Web.Infrastructure.AccountRoleProvider" />
      </providers>
    </roleManager>
...
  </system.web>
...  
</configuration>

It really us as simple as that!

One other note, if you are implementing your own password storage, make sure you hash them! (and I recommend you look at bcrypt for that).

ReactiveUI Property Name to Field Mapping Convention Override

In a previous post I described how you can use the ReactiveUI framework to bind properties to both INotifyPropertyChanged and make them Observable to Reactive Extensions (Rx).

The default binding behaviour of the RaiseAndSetIfChanged helper is to assume that a property named “MyProperty” has a backing field called “_MyProperty”. This is not a common convention, and whilst you can explicitly override this behaviour in RaiseAndSetIfChanged, it’s extra work.

Fortunately, the framework offers a way of modifying the default mapping behaviour by binding a different function to RxApp.GetFieldNameForPropertyNameFunc.

Here are a couple of example functions that implement alternative behaviours. The first of which maps to _propertyName and the latter, simply topropertyName.

                /// Maps property name MyProperty to field name _myProperty.
                Func<string, string> UnderscoreFirstToLowerBehaviour = x =>
                {
                        char[] arr = x.ToCharArray();
                        arr[0] = char.ToLower(arr[0]);
                        return '_' + new String(arr);
                };

                /// Maps property name MyProperty to field name myProperty.
                Func<string, string> FirstToLowerBehaviour = x =>
                {
                        char[] arr = x.ToCharArray();
                        arr[0] = char.ToLower(arr[0]);
                        return new String(arr);
                };

To use one of these behaviours, all you need do is call the following once during app startup:

RxApp.GetFieldNameForPropertyNameFunc = underscoreFirstToLowerBehaviour;

Given this is executed on each notification, I guess the second coding style is more optimal!

p.s. I’m not sure these are the fastest implementations of these conversions, and I’m not going to benchmark, however I did base the code on http://www.dotnetperls.com/uppercase-first-letter who did do some benchmarking on similar code.

A Retry Helper Class with Exponential Backoff

Just a small snippet here. It’s sometimes useful to have some retry logic when talking to web services etc. This little helper class does just that whilst implementing exponential backoff:

	public class RetryHelper<T>
	{
		private static readonly ILog log = LogManager.GetLogger(typeof(RetryHelper<T>));
		
		public T Value { get; protected set; }

		/// <summary>
		/// Performs an operations returning a type of T. Should the operation throw an exception, it will be 
		/// retried after the retry interval. The backoff is exponentional on each retry.
		/// e.g. string res = RetryHelper{string}( () => myFunc(myParam1, myParam2), 5, 500).Value;
		/// </summary>
		/// <typeparam name="T">Return type of function to add retry semantics to.</typeparam>
		/// <param name="func">The function delegate.</param>
		/// <param name="maxAttempts">Number of times to retry the operation.</param>
		/// <param name="baseMillisecondsInterval">The interval of the first retry, will double upon each attempt.</param>
		public RetryHelper(Func<T> func, int maxAttempts = 5, int baseMillisecondsInterval = 500)
		{
			int retryInterval = baseMillisecondsInterval;

			for (int attempt = 1; attempt <= maxAttempts; ++attempt)
			{
				try
				{
					Value = func();
					return;
				}
				catch (Exception ex)
				{
					log.ErrorFormat("Failure executing operation (Attempt={0}) : {1}", attempt, ex.Message);
				}

				System.Threading.Thread.Sleep(retryInterval);

				retryInterval *= 2;
			}

			throw new ApplicationException(string.Format("Exhausted retries (Attempts={0})", maxAttempts));
		}
	}

This code is dependent on log4net, but you can of course remove that.

To use it, all you need to do is:

string MyFunc(int i, string s)
{
	...
}

...

string res = new RetryHelper<string>( 
	() => MyFunc(myParam1, myParam2)).Value;

It’s worth noting that exponential backoff for network code often randomises the retry interval to prevent packet collisions. This example doesn’t, but there is nothing stop you from doing that.

Using ReactiveUI to Integrate INotifyPropertyChanged & IObservable

ReactiveUI offers some great helper functionality for integrating Reactive Extensions into your WPF user interfaces.

One of these is the ReactiveObject base class, which when derived from, grants your classes access to the ‘RaiseAndSetIfChanged’ helper function.

This conveniently wires up your properties to INotifyPropertyChanged/IObservable, so in one step you have a class that can be bound directly to your xaml AND observed using Rx.

	class Person : ReactiveObject
	{
		string _Name;
		public string Name
		{
			get { return Name; }
			set { this.RaiseAndSetIfChanged(x => x.Name, value); }
		}
	}

By convention ReactiveUI expects the backing field to have the same name as the property, but with an underscore prepended. So if you want a different backing field name, you have to explicitly reference it in RaiseAndSetIfChanged:

	class Person : ReactiveObject
	{
		string _name;
		public string Name
		{
			get { return _name; }
			set { this.RaiseAndSetIfChanged(x => x.Name, x=> x._name, value); }
		}
	}

The obvious question is then, ‘how do we subscribe to changes on these properties?’. The secret is to use the ReactiveObject base class function ObservableForProperty.

In the example below, we are doing something a little more complex that simply watching one property. Instead we are observing two properties containing cash amounts, and automatically updating a total when either changes.

	class Dividend : ReactiveObject
	{
		decimal _AnnouncedAmt;
		public decimal AnnouncedAmt
		{
			get { return _announcedAmt; }
			set { this.RaiseAndSetIfChanged(x => x.AnnouncedAmt, value); }
		}

		decimal _ForecastAmt;
		public decimal ForecastAmt
		{
			get { return _forecastAmt; }
			set { this.RaiseAndSetIfChanged(x => x.ForecastAmt, value); }
		}

		decimal _TotalAmt;
		public decimal TotalAmt
		{
			get { return _totalAmt; }
			set { this.RaiseAndSetIfChanged(x => x.TotalAmt, value); }
		}

		public Dividend()
		{
			Observable
				.Merge(	this.ObservableForProperty(x => x.AnnouncedAmt),
						this.ObservableForProperty(x => x.ForecastAmt))
				.Subscribe(_ =>  TotalAmt = AnnouncedAmt + ForecastAmt);
		}
	}

You’ll notice that the lambda parameter in the subscribe is an ‘_’, this is a functional programming convention for naming parameters that are not used in the lambda function.

There are a couple of advantage with this approach:

  • Clean and simple property get/set methods. The alternative implentation would either have to update the total in the setters, or even more verbosely, and unlikely in practise, listen on the INotifyPropertyChanged interface.
  • External code can also bind to changes on these properties. We’ve implemented the Observer pattern with very little code or overhead

ReactiveObject makes a great base class to derive your MVVM view models from.

10 Print “Hello World”

Hello, and welcome.

I’m a professional software developer, who has worked in the investment banking sector for the majority of my career. I started programming rather earlier than that though, taking my first tentative steps aged 8 on a BBC Micro.

I still remember going into Dixons consumer electronics store, and using the display computers to create such wonders as:

10 Print "Hello World!"
20 Goto 10

Well… we all had to start somewhere!

As a lead developer and team lead, I regularly find myself needing to teach or write up tutorials for internal distribution. Rather than share these solely with colleagues, I’ve decided to reach a wider audience hopefully helping others and benefiting from constructive feedback.

I’m interested in a variety of technologies, but at the moment I’m predominantly focussing on:

  • Architecture & Design
  • C#/.net 4.0
  • WPF, particularly MVVM patterns
  • Reactive Extensions (Rx)
  • Task Parallel Library (TPL)
  • Asp.net MVC 3
  • MongoDB
  • GeoLocation

So these are likely to be the main topics of this blog, at least initially.