GetType() can lie?

Nice question! The way I see it, you could only really mislead a fellow developer if GetType was virtual on object, which it isn’t.

What you did is akin to shadowing GetType, like this:

public class BadFoo
{
    public new Type GetType()
    {
        return typeof(int);
    }
}

with this class (and using the sample code from the MSDN for the GetType() method) you could indeed have:

int n1 = 12;
BadFoo foo = new BadFoo();

Console.WriteLine("n1 and n2 are the same type: {0}",
                  Object.ReferenceEquals(n1.GetType(), foo.GetType())); 
// output: 
// n1 and n2 are the same type: True

so, yikes, you’ve successfully lied, right?
Well, yes and no… Consider that using this as an exploit would mean using your BadFoo instance as an argument to a method somewhere, that expects likely an object or a common base type for a hierarchy of objects. Something like this:

public void CheckIfInt(object ob)
{
    if(ob.GetType() == typeof(int))
    {
        Console.WriteLine("got an int! Initiate destruction of Universe!");
    }
    else
    {
        Console.WriteLine("not an int");
    }
}

but CheckIfInt(foo) prints “not an int”.

So, basically (back to your example), you could really only exploit your “lying type” with code that someone wrote against your IFoo interface, which is very explicit about the fact that it has a “custom” GetType() method.

Only if GetType() was virtual on object you would be able to craft a “lying” type that could be used with methods like CheckIfInt above to create havoc in libraries written by someone else.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)