Tuesday, 19 June 2012

C# Type Confusion - tricking the compiler to view a String as a StringBuilder (or a TextBox as a Label)

One of the less known security implications of the fact that the .NET verifier is disabled when executing code in FullTrust (which is the default) is the fact that the type-safety of the code executed is mainly enforced by the compiler and not (as expected) by the CLR (which is the case when the verifier is enabler).

'Type Confusion' happens when we are are able to cast an Class A object into a Class B type,  without triggering an compilation or runtime error. Under normal behaviour, we would get an compilation error since Class A and Class B are not compatible classes.

We are basically trying to do this (which breaks 'type safety'):

String a = "";
StringBuilder b = (StringBuilder) a;

Here is a C# code sample that shows a number of examples around an specific Type Confusion scenario:


Extension method used:


Code that creates the DLL which does the type confusion:


Here is a different example where I was able to cast an TextBox as a Label:


Although we can can cast any object into any type, if the memory values don't align, we will end up crashing the runtime :)

For example, casting a TextBox as a ToolStripTextBox

Triggered this error:

And this one:

So yeah, we have to be careful, but I already have a number of places I can use this technique inside the O2 Platform (for example when reusing dynamically compiled objects which from the CLR point of view are created in different assemblies, and are treated as incompatible)


Related Posts: