Properly storing password (Hashing and Salting)

site-securityPasswords should never have been stored as plain text, but they were and when databases were compromised there was no protection. Then again people shouldn’t reused passwords but they do, all the time. However with services like LastPass, 1Password and iCloud keychain hopefully people will start to shift away from reusing simple passwords. Regardless we as developers should err on the side of caution and always ensure that when we store passwords it’s in a way that prevents anyone who would happen to get them to use them maliciously.

The simplest and recommended way to do this is by cryptographically hashing the passwords before storing it. Hashing is the action of taking a message of variable length and computing a fixed length representation of the message, while also ensuring that every message only generates one hash. A cryptographic hash has four main properties that benefit it’s use as a method to secure passwords.  The hash value for any given message is easy to compute, while being infeasible to generate a message that has a given hash, infeasible to modify a message without changing the hash, and infeasible to find two different messages with the same hash.

It should also be noted that it is generally unfeasible to reverse a hash, I say unfeasible as given enough time and computational power you could employ a dictionary attack or pre-computed rainbow table attack.  Both these methods however can be mitigated by salting, salting is the process of adding random data to password before it’s hashed.  A new salt is randomly generated each time and is stored with the hashed password in a database.

Now lets look at how to implement this, starting by the hashing function itself.

private static byte[] Hasher(string password, byte[] salt, int iterations, int length)
{
   Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations);
   return pbkdf2.GetBytes(length);
}

The inputs to the function are:

  • password: The users unencrypted password
  • salt: The random data we will be generating and storing with the hash
  • iterations: the number of times the function should run, the idea being more iterations the stronger the hash becomes.
  • length: how long do you want the hash to be in bytes

The function starts by initializing an instance of Rfc2898DeriveBytes named PBKDF2 (Password-Based Key Derivation Function 2) with the password, salt and number of iterations. This will generate the hash, finally the function returns the hash.

Now that we have our private hashing function lets create two a public functions one to create the hash another to verify it.

First lets create some constants as no one likes magic numbers

public const int SALT_BYTE_SIZE = 24;
public const int HASH_BYTE_SIZE = 24;
public const int ITERATIONS = 20000;

To keep is easy we will create salts and hashes with a length of 24 bytes and lets set the iterations to 20000, always benchmark your server you want to keep the iterations high but not so high that users have to wait for minutes while you check their password.

public static string CreateHash(string password)
{
   RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider();
   byte[] salt = new byte[SALT_BYTE_SIZE];
   csprng.GetBytes(salt);
   byte[] hash = Hasher(password, salt, ITERATIONS, HASH_BYTE_SIZE);
   return Convert.ToBase64String(hash) + ":" + Convert.ToBase64String(salt);
}

The first line create a cryptographic Random Number Generator in this case CSPRNG (cryptographically secure pseudo-random number generator). The second a byte variable to hold the salt and the third fills the salt with random bytes from the number generator.

Now that we have the password and a salt we can call Hasher function and generate our hash and return the hash and salt.

public static bool Validate(string password, byte[] hash, byte[] salt )
{
   byte[] testHash = Hasher(password, salt, ITERATIONS, HASH_BYTE_SIZE);
   uint diff = (uint)hash.Length ^ (uint)testHash.Length;
   for (int i = 0; i < hash.Length && i < testHash.Length; i++)
      diff |= (uint)(hash[i] ^ testHash [i]);
   return diff == 0;
}

To validate a password we need the password from the user, and the hash and salt from the database passed into the Validate function, the first line of the function then creates a testHash using the password entered by the user, and the same salt that was used to create the original hash, if the salt has been modified then the hashes will not match even if the correct password is entered.

Once the testHash has been created we start checking if both hashes have the same length using a bitwise exclusive-OR.  Once we know the hashes are the same length we step through them comparing byte to byte using an bitwise exclusive-OR and setting diff using OR assignment that way if a single byte is different the function will return false.

And there you have it, simple secure password protection.

Microsoft Xbox One

I, along with many others, recently bought Microsoft’s newest foray into the console market, the Xbox One.

Now I have to say as someone who’s owned a NES, Genesis, SNES, N64, Playstation, Xbox, Gamecube, Playstation 2, Wii, Xbox 360, Playstation 3, Wii U, and now the Xbox One it is a fantastic console. It’s incredibly quiet and while it’s boot up time can be a little on the long side you don’t ever really have to turn it off and that is what Microsoft wants.  Their idea is that the Xbox One is more than just a gaming console, they want it to be the centre of your home entertainment.

I understand that for most people who only have a TV, a cable box, and maybe a sound system, the Xbox One will fullfill 100% of your home entertainment needs.  The Youtube & Netflix apps are great, I’m certain others like Vimeo and Vevo are working on apps, if they aren’t … they should be.

The Xbox One has an HDMI input port, meaning you can connect your cable box to the console and then use OneGuide to navigate the channels via voice or controller, sadly these features are not available in Canada.

And that’s not where my problem ends … I have a total (including the Xbox One) of seven devices that feed into my TV via a Tuner and HDMI Switch and while the Xbox One can be configured to turn my TV and Tuner on when the “Xbox On” command is uttered there is no way to configure what HDMI port any of the devices should be set to, something that should be added in.

Microsoft should go one step further, the new Kinect has a an IR blaster that could be used to control all of my devices.  An advanced TV setup mode should be added where the user is guided through identifying all of their devices, including how they are connected.  This would enable the Xbox One to be the true centre of my home entertainment, using commands like Xbox watch DeviceX the Xbox One could know to change the HDMI switch to input #3 and the Tuner to input #1.

For now it will continue to simply be one of the many devices plugged into my tuner and controlled from my logitech universal remote.

A very special woman in my technology history

With all of the talk about women in computer programming, I wanted to talk about a very important woman in my computer programming history, my mother.

Before I start, I first have to say that my mother never saw an activity as being for one specific gender, hence, this is why I was in Figure Skating and Downhill Racing as a child.

While working at Eaton’s as a purchasing agent for the Eastern Canada stores (1975), my mother was also attending McGill University completing a commerce degree. During this time she was introduced to computers and computer programming by using punch cards to code cobol and fortran. My mother is the first to admit she wasn’t good at typing and considering there was no backspace on the typewriters she burned through a lot of cards.

PastedGraphic-2
She used to tell me stories of having to wait 40 minutes to find out she forgot a single character. She eventually learned that the Engineering faculty had gotten a deckwriter that would allow her to not only code, but also amazingly run her code without waiting to find out if she missed something. She also recounted when the school brought in their first personal computer, something that at the time was both rare and extremely expensive.

My mother eventually started keeping the books for her father’s Esso service station, by the books I mean the stacks and stacks of paper and inventory cards. She somehow convinced the bank to give them a loan in order to buy a PC so she could computerize their accounting and inventory system, something that must have sounded right out of science fiction for a bank in 1979. Not only was she able to computerize the books, saving the garage, but it propelled my Grandparents to having a very successful business.

imgres
Eventually my mother started working for the Canadian federal government as an auditor, in what at the time was the department of customs. Her knowledge of computers and programming quickly became an asset and she was able to get a portable computer so she could build auditing programs while on the road performing audits.

At this point, she had also started assembling her own personal computer and this is where I come in. I was fortunate and privileged to be brought up in a household with a PC as a child. I would play PC games, and when I was old enough, would load up dBase2 and play around.

If it had not been for my mother, her introduction to computer science while in school, and her passion for computers and programming, I may have never become a computer programmer myself.

As such I’m more then happy to make a donation to the Ada initiative especially with the matching donation challenge that’s currently happening.

Surface Pro as gaming tablet?

 

3286_Surface_ProEarlier this week I finally picked up Microsoft’s newest tablet computer, and I must say I’m very impressed.

One of the biggest reasons I switch to a Mac years ago what the quality and design of the hardware. It’s a shame that it toke Microsoft themselves to clue into this and finally show the OEMs how to make a decent tablet.

Regardless I had read countless reviews on the speed and design of the Surface Pro so while it was refreshing to see they were true.

I decided to test what in mine opinion, and the windows experience apparently, was the weakest link the Intel 4000 graphics chip.

surprised_cat

I didn’t take it easy by only playing some Metro games like cut the rope and fruit ninja ;) the first game I loaded up was the new reboot of Tomb Raider.  I was expecting a choppy mess that would require me to hard reboot do to being unable to even use the menu ;) To my surprise it ran, not only did it run but once I plugged in a USB Xbox controller, more on why later, it was almost playable, scenes with a lot of action were unplayable.

Next I loaded up Bioshock Infinite while it was no were as playable as Tomb Raider I was able to make it all the way to Columbia and explore, once combat started… I was dead meat.  Farcry 3 same story the game ran and was a choppy at times, Borderlands 2 same results

Ok maybe I had pushed the intel 4000 chip to it’s limits, what about some older games?  I consulted my steam library and started to install Bioshock.  Not only did run it was fully playable :) How about something a little more recent like Borderlands 1… yup playable :)

Now while playing all these games the first thing I tried to do was use the touchscreen, then type cover before resorting to a game controller or USB mouse and keyboard.  I can say that sadly none of the games were able to function with the touchscreen (not to my surprise) and that the type cover wasn’t able to handle using the track pad and keyboard at ones.

Overall is the Surface Pro a great tablet, yes, is it a gaming computer no but you can sit back and play some old favorites and new games designed to make use of it’s touch screen.  I was impressed that it could even load up some of the newest games on the market.

(All games were first played at 1920×1080 with settings set to low and then increased if the game ran smoothly)

Updated

On the recommendation of Diarmuid Murphy I installed Civilization 5 and wow… not only is the Surface able to play it well but the windows 8 touch screen support is awesome!

20121105024039_civ 5 touch interface_2012-11-05_00001

After having played Civ 5 with touch controls I want it in more games, obviously some games aren’t meant for it but anything turned based could greatly benefit from this!

Wearable computing

I just recently received my Pebble and after a few days with it I must say I can’t imagine not having it strapped to my wrist.

Is it perfect? No, like any other first generation product it has some flaws that need to be worked out. Thankfully the team behind the Pebble thought of this and designed the watch so it’s software can be updated.

The watch when paired over bluetooth (2.1 + ERD) allows your cell phone to push notifications directly to your wrist :) now when i fell my phone buzzing I don’t have to pull it out of my pocket i can simply glance at my wrist and see is it something that I need to action or something that can wait.

20130226-145656.jpgCurrently the phone can receive new “watch-faces” via the smart phone app but in the future Pebble has stated that they will release an SDK that will allow developers to build apps, like the music remote control app that is built into the watch. Until this SDK and App Store is available the watch will be less a wearable computer and more of an interface to my pocket computer.

And Pebble is not alone, Google announced Project Glass at I/O 2012 and is looking at shipping it in Q4 of 2013. While Google says they will be shipping a finished product anyone who’s used Android back in it’s early days, even the newest version to some extent, knows that Google is the king of the perpetual beta.

The last item I’m excited about is the Myo it’s a bluetooth bracelet that will translate hand gestures into actions on, hopefully, any device. Personally I feel that this is how Google Glass should be controlled not via voice but through gestures, the reality is that talking to one self in a public setting is never desirable.

It will be interesting to see if and how Apple joins in on wearable computing.

 

What is Startup Experience?

startup-sign

 

I was reading the careers page on Shopify today and saw “Startup Experience” listed under Desired Skills. Initially I dismissed it as I’ve been working in the Government for 10 years.

Then I started thinking, during my 10 years within the government have I experienced anything that could be considered as such… Then it hit me, yes, now it’s not your traditional start up experience but in my opinion it fits the bill.

A few years ago, after showing my bosses how quickly I could prototype applications, it dawned on them that A) there was no way our department would allow them to run as they were not built by their IT staff and B) other departments would need the same applications.

I’ll skip the boring part where we had to sell the idea to management, suffice it to say we got the funding and approval to go ahead.

We all knew that we had to deliver a product that either reduced cost or improved service delivery or else… As such, in a matter of months we secured a hosted environment, gathered business requirements from multiple departments, built a prototype, and finally a product to pilot with multiple departments. This meant long days and nights and it payed off, not only was our initiative a success, it was even recognized as such by a number of groups (HR Submit 2012 Award – Corporate Governance and Strategic Leadership Award and GTEC 2010 Distinction Awards Medalists – Unique Achievement)

So what do you think? Does it sound like my experience was similar to that of a Startup?

Updated

Marc Gagne sent me an interesting link: Intrapreneurship. I was not surprised to see the Lockheed Martin “Skunk Works” group as the first example, this is exactly what my group was at the start.

Simulating Scheduled Tasks with HttpRuntime Cache

Image taken from http://picardfacepalm.com/

Image taken from http://picardfacepalm.com/

Recently at work I was tasked with something that sounded simple enough build a web app that would send out email one a schedule.

Then I realized that I can’t use a web service, scheduled job or basically anything other than a simple web app.  The reason for this is that I don’t even deploy my own apps at my current job.  I compile my code and send it off to have it deployed.

I set out to accomplish this using only a web app.

First web apps are normally something that responds to an events, since I can’t use a scheduled task I’ll had to find a way for the application to trigger itself.

After some hunting on the web I found several articles/code samples some used a thread others used the HttpRuntime class and the application cache.  It looked surprisingly simple and so I had to try it and see if it worked.

Since I want my schedule task to always be running i decided the best place to start it up would be in Global.asax.vb as such I added it to my project and started coding.  The end result was the following:

Imports System.Web.SessionState
Imports System.Web.Caching

Public Class Global_asax
    Inherits System.Web.HttpApplication

    Dim onRemove As CacheItemRemovedCallback

    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        AddTask("BackgroundTask", 60)
    End Sub

    Sub AddTask(ByVal name As String, ByVal seconds As Integer)
        onRemove = New CacheItemRemovedCallback(AddressOf Me.RemovedCallback)
        HttpRuntime.Cache.Insert(name, _
                                 seconds, _
                                 Nothing, _
                                 DateTime.Now.AddSeconds(seconds), _
                                 Cache.NoSlidingExpiration, _
                                 CacheItemPriority.High, _
                                 onRemove)
    End Sub

    Public Sub RemovedCallback(ByVal k As String, _
                               ByVal v As Object, _
                               ByVal r As CacheItemRemovedReason)
        If k = "BackgroundTask" Then
           'This is where you can run your code
           AddTask(k, Convert.ToInt32(v))
        End If
    End Sub
End Class

On Line 7 I’m creating a class wide CacheItemRemovedCallback variable called onRemove this variable will be used later to tell the application what sub procedure to call when an item is removed from the cache.

In the Application_Start (Lines 9-11) I’m calling AddTask, as the application is only started once this eliminates the need for me to check and ensure that my task hasn’t already been added, and important step if your using this idea somewhere else then in Application_Start.

Next is the AddTask sub procedure (Lines 13-22) I’ve formatted it for this post but it’s essentially two lines, the first creates a new CachedItemRemovedCallback and passes in the address of the RemovedCallback sub procedure.  The second inserts a new item into the HttpRuntime Cache the full details can be found on MSDN the important part in this code is that we set the key to the name of our task (Line 15), the value to the frequency we want it to repeat (Line 16), it’s expiry to the current time plus the frequency (Line 18) and our CacheItemRemovedCallback variable (Line 21).

What this will do is add an item into the cache set to expire in 60 seconds, once it expires it will call the RemovedCallback (Line 24-31) procedure and pass into it the key, value and reason. This is where we can now check that the item removed is the same as we added (Line 27) and perform our task (Line 28) lastly to ensure this task runs again in 60 seconds we call AddTask and pass in the same values (Line 29).

And voila you application will now run this “task” every 60 seconds.

Now we only have two little problems to deal with what happens if you application does ideal and IIS end’s it and what happens with IIS recycles the application pool… The solution, after many experiments was to create a second web app.  Considering what function this web app would do I decided to call it the FrontDesk since my main app would call it and request a wakeup call.

to call it I added the following code into another sub procedure and called it from the Application_End sub procedure.

    Public Function PingServer(ByVal URL as String) As String
        Try
            Dim request As WebRequest = WebRequest.Create(URL)
            request.UseDefaultCredentials = True
            request.PreAuthenticate = True
            request.Credentials = CredentialCache.DefaultCredentials

            Dim response As WebResponse = request.GetResponse()
            Dim dataStream As Stream = response.GetResponseStream()
            Dim reader As New StreamReader(dataStream)
            Dim responseFromServer As String = reader.ReadToEnd()
            Return responseFromServer
        Catch ex As Exception
            Return "Error:" & ex.ToString
        End Try
    End Function

Essentially this PingServer sub procedures fetches the website of any URL you pass into it, this has the added benefit of waking up any .net web app.  The FrontDesk web app simple takes in a URL via the QuerryString sets up a task 30 seconds in the future, in order to allow the application to end gracefully, then using the same PingServer method wakes up the main application.

This is by no means how I would ever suggest you should do scheduled tasks unless you have no alternative, also something to note this application will be run within a private network as such I couldn’t use any solution that would be coming from outside the network.

How I built the Peanut Gallery windows 8 app in minutes

20130103-100922.jpg

To be fair the only reason I can say built is that I had to build and publish the app, all of the hard work was done for me.

I used MetroPress and the step by step instructions found on the IdeaNotion website

Now I ran into one problem and it was of my own making, being a lazy blogger I had not setup any categories and was filing everything into “uncategorized” turns that the JSON plugin and MetroPress decided that this was unacceptable and did not populate the app.

But once I categorized my apps and refreshed the app voila all my posts appeared.

I then created some simple graphics for the app, toke screenshots and submitted the app to Microsoft. The app was reviewed in approved in what for me is a new record, especially considering this was during the week of Xmas.

The Peanut Gallery app is now available and will be supplied with a new posts on a regular basis.

DVLUP

Screen Shot 2012-12-23 at 1.20.51 AM

I’ve recently received an invitation into the Nokia DVLUP Beta program, I must say the fine people at Nokia have outdone themselves.

I’ll post more about it but I’ll just start with say wow… I want some of those rewards and with the challenges such as “Pointstravaganza: Update your apps and games to Windows Phone 8″ rewarding anyone who updates a Windows Phone 7 app to Windows Phone 8 with a 1000xp it’s easy to get to the 6250xp required to get a free Nokia Lumia 920.

I’ve already updated both my apps and submitted them :)