daveBlog

There is a madness to my method…

View My GitHub Profile

Follow me on Twitter

Come work with me!

Site feed

Decoding Forms Authentication Cookies With Mono

Lately, I’ve been experimenting with migrating web services from .NET on Windows to Mono on Ubuntu. While getting the code building and running in a VM was not terribly difficult, I soon found that authentication was a roadblock.

Our web services run across several subdomains. We’re moving towards using OAuth for everything, but many services still use Forms Authentication with a cookie that is shared across all subdomains. However, when I tried to use my cookie with a service running on Mono, I was treated as an unauthenticated user.

The first barrier to shared authentication between .NET and Mono is actually well-documented: the default cookie name under Mono is .MONOAUTH, rather than .ASPXAUTH. Upon discovering this, I quickly modified my Web.config to explicitly set the cookie to .ASPXAUTH…and nothing happened.

Another early discovery was that Mono base-64 encodes the cookie, while .NET uses base-16. Again, changing this (in my case, by using a custom build of Mono) had no effect—I was still treated as an unauthenticated user.

Eventually, after quite a bit of digging around, I learned that the binary format for .NET’s Forms Authentication cookie is undocumented, so Mono had to implement a reasonable—yet incompatible—alternative format. Furthermore, if you choose to encrypt the cookie, .NET adds an extra 28 bytes of padding to the cookie using an unspecified hash function—my best guess is that this has something to do with avoiding hash collision attacks.

In any case, I spent a lazy Saturday afternoon poking around with the format and arrived at a method of decoding the cookie, which is included here for your reading pleasure:

As you can see, it’s very proof-of-concepty, and it assumes specific encryption and signing algorithms, but it gets the job done and should be pretty easy to extend and generalize. Just drop this code into your Global.asax.cs, provide your favorite implementation of base-16 string to bytes, and you’re good to go.

Happy hacking!

Building Mono on Mac OS X (2011 Edition)

Quite a bit has changed since I wrote my post a few years ago on building Mono for OS X. So much has changed, in fact, that I've decided that a new post on the topic is in order. These instructions assume that you're using Snow Leopard. They should work on Leopard with minimal changes, but your mileage may vary.

Prerequisites

Installing the prerequisites for Mono is much simpler than it once was. Previously, Mono had external dependencies like glib, which would mean you'd need to install MacPorts, but they've taken steps in the last year to reduce and eliminate such dependencies.

Git

If you haven't yet heard about git, stop hiding under that rock! The Mono source is hosted on GitHub, so if you want to download and build it, you'll need a copy of Git. You can acquire it here.

XCode

XCode 4 is now a $4.99 download in the Mac app store. If you're too cheap for that, you can still (as of the time of this writing) grab XCode 3 here (free registration required). A copy may also be on one of the discs that came with your Mac.

Mono

While you can (theoretically) bootstrap Mono, it's not something I recommend unless you enjoy pain. Save yourself some trouble and download the latest version here.

Get the Source

The Mono source code is now hosted on GitHub. Open your Terminal and clone the repository by issuing the command

git clone git://github.com/mono/mono.git

Build and Install

First, you'll need to run autogen.sh. Here's how I usually invoke it:

./autogen.sh --with-sgen=no --with-xen_opt=no --prefix=/opt/mono-`git rev-parse HEAD` --with-mcs-docs=no --disable-nls

My rationale for each option is listed below.

  • --with-sgen=no: The Mono team considers the SGen garbage collector to be production ready, but I've had problems with it, so I still turn it off.
  • --with-xen_opt=no: I'm not running Xen, so there's no need for this.
  • --prefix=/opt/mono-`git rev-parse HEAD`: You may want to just use --prefix=/opt/mono. I include the git revision in the path to make it easier to keep a number of parallel installations around for testing purposes.
  • --with-mcs-docs=no: The documentation takes a while to build and generally won't be much different than what's in your installed copy of Mono. Save yourself some time and leave it out.
  • --disable-nls: I don't need this particular feature. If you do, leave it in.

Assuming that autogen.sh completes successfully, you can now build it with

make -j1

Depending upon how your development environment is set up, you may not need the -j1. However, if your default MAKEFLAGS has a different -j option, you'll want to use this. Otherwise, the Mono build can fail in strange ways. Once this is done, run sudo make install, and you'll be all set!

Rewrite History with git-filter-branch

I've found this page useful on a few occasions, so I'm linking it from here so that I don't forget where it is.

The author demonstrates how to use git-filter-branch to completely remove files from a git repository. I haven't felt compelled to take all the steps that he does in order to get rid of the files, but it's an excellent reference for the command, nonetheless.

Customized URLs in Rails with to_param

This is probably one of the most basic concepts for experienced Rails developers, but I had a hard time finding what I was looking for on Google, which means that other people are having a hard time too, so here's my first little contribution to the Rails community…

I recently moved from SubText to a tiny little (incomplete!) blog engine that I wrote for myself in Rails. While working on it, I was also reading a little bit about SEO; one of the concepts expressed was that each url on your site should have something to do with the content of the page to which it refers. While Rails has good defaults for a lot of things, a url like http://example.com/posts/123 certainly leaves room for improvement.

While I knew that I could accomplish the affect that I wanted by creating a bunch of custom routes in routes.rb, I wanted to be able to take advantage of map.resource and methods such as link_to, which seemed to insist upon using the record ID of my ActiveRecord model.

Until I found to_param.

to_param, as it turns out, is a very simple method that you can override in any ActiveRecord model. Whatever value you return from this method will be used in any urls generated by methods like link_to. The one caveat is that after you do this, you must change the code for any of your controllers so that they look up records based on this new external ID. In many cases, this may be as simple as changing MyController.find(params[:id]) to MyController.find_by_name(params[:id]).

Objective-C Reference Counting From the Bottom Up

I've been interviewing a lot of Objective-C developers, lately. In my mind, one of the most fundamental parts of working with Objective-C is understanding how reference counting works, and I'm consistently surprised by how many people are unable to clearly describe it. In this post, I'll outline the absolute minimum that anyone working with Objective-C ought to know about reference counting. If you find yourself in an interview with me, and you can describe everything in this blog post, I'll know where you got your information you'll be doing better than most.

The Basics

Objective-C objects are reference counted. This means that each object comes with a little counter, and anyone can modify the value of this counter by calling retain (to increase the value) or release (to decrease the value). When the value of the counter reaches 0, the dealloc method is called on the object, and any memory associated with the object is reclaimed by the system.

A good developer will make use of this system by calling retain on objects whose pointers are being stored in other objects and calling release on those objects when the pointer no longer needs to be stored. This is, in fact, the reason that we call it "reference counting": the counter is intended to indicate how many objects (or, in some cases, global variables) are holding references to the object.

Deadly Embraces and Retain Cycles

When two objects each call retain on the other, we call it a "deadly embrace": if no other action is taken, the objects will never be deallocated. This is widely regarded as a "bad thing".

When this sort of pattern occurs with more than two objects (for example, A retains B, B retains C, and C retains A), it is called a "retain cycle", and these can be even nastier to deal with.

Deadly embraces and retain cycles are dealt with by either preventing one object in the cycle from retaining its "parent" or by having explicit cleanup logic that is executed when it is certain that the objects are no longer needed. Really elite developers sometimes create proxy objects to stand in for one of the objects, although a full discussion of this technique is beyond the scope of this post.

Autorelease

The autorelease method is perhaps the most widely misunderstood concept in Objective-C memory management, although in practice, it's actually relatively simple.

At the beginning of each iteration through your application's run loop, an NSAutoreleasePool is created. At the end of each iteration it is destroyed. You can also create and destroy NSAutoreleasePools anytime you wish to do so (for example, you generally need to manually create and destroy them in background threads; more on this, later).

When you call autorelease on an object, the object searches for the most recently created NSAutoreleasePool in its thread. Assuming that it finds a pool, it adds itself to the list of objects that need to be released. When the NSAutoreleasePool is destroyed, it calls release on each object that is in its list--if an object is listed multiple times, release is called multiple times. If the object fails to find an NSAutoreleasePool, a message is logged to the console and the object is leaked (this is why you need to create an NSAutoreleasePool when doing work on a background thread).

Ownership and Object Creation

While the notion of "ownership" is not baked into the semantics of Objective-C, one object can be thought to "own" another if it has called retain on the object or has created an instance of the object via the alloc or copy methods. An object that owns another is responsible for calling release on that object when it is no longer needed.

This brings us to an interesting question: what should be done for a method that creates an object but isn't called alloc or copy? In order for the object to be active, its retain count must be at least 1, but the calling method cannot be relied upon to call release.

The answer, of course, is to use the autorelease method. This allows the retain count to be a non-zero value when the method returns, and if nothing is done to keep the object alive, it will be reclaimed when the active NSAutoreleasePool is destroyed.

Property Getters and Setters

Care must be taken when writing a method that sets a property value. The naive implementation of such a method looks like this:

- (void)setProperty:(id)value
{
	[propertyField release];
	propertyField = [value retain];
}

This is bad: if value is the same as propertyField, and the retain count of this object is 1 when we enter the method, the first line of the method will cause the object to be deallocated, and the second line will cause bad things to happen (although bad stuff may not happen immediately, which is worse).

This problem can be worked around by retaining value before releasing propertyField, by ensuring that the values are not equal to each other before performing the operation, or even by autoreleasing propertyField instead of releasing it (although this adds overhead).

Another interesting problem in this space involves methods that get property values. Again, the naive implementation of such a method looks like this:

- (id)property
{
  return propertyField;
}

99 times out of a hundred, this will work fine. This of course means that when you run into that one time it doesn't work, it's going to be a huge pain to debug. Here's the case in which you can get into trouble:

id foo = [obj property];
[obj setProperty:bar];
[foo doSomething];

If the retain count of propertyField is 1 at the beginning of this block, then the second line will cause it to drop down to zero and be reclaimed. This means that the third line will be performed on an object that has been deallocated, which is, to say the least, less than ideal. The solution to this is to modify the property getter so that it calls retain and autorelease on propertyField before returning it. This has no net effect on the retain count of the object, but it does ensure that the object will stay alive at least until the active NSAutoreleasePool goes out of scope.