Is it possible to trick this WindowsIdentity code into using the wrong user?
See the question and my original answer on StackOverflowTo demonstrate this is doable, let's use a cool Visual Studio addon named "Microsoft Fakes" (the name itself means a lot...).
Fakes itself is tied to test features of Visual Studio, but it will prove the point. You can follow the standard tutorials to setup a project, and add a fakes assembly for System (in fact mscorlib + system)
This is your code in a library project (I've used exception everywhere because it's easier in testing condition...).
namespace ClassLibrary1
{
public class Class1
{
public static void MyCheck()
{
WindowsIdentity identity = Thread.CurrentPrincipal == null
? null
: Thread.CurrentPrincipal.Identity as WindowsIdentity;
if (identity != null && identity.IsAuthenticated && !identity.IsAnonymous)
{
var validated = new WindowsIdentity(identity.Token);
if (!validated.User.Equals(identity.User) || !validated.IsAuthenticated || validated.IsAnonymous)
throw new Exception("Something fishy is going on, don't trust it");
else
throw new Exception("Good! Use the validated one. name is:" + validated.Name);
}
else
throw new Exception("not in");
}
}
}
This is the testing code in the test project:
namespace UnitTestProject1
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
using (ShimsContext.Create())
{
System.Security.Principal.Fakes.ShimWindowsIdentity.AllInstances.NameGet = (i) =>
{
return "Simon the hacker";
};
WindowsIdentity wi = WindowsIdentity.GetCurrent(); // this is the real one "Simon".
Thread.CurrentPrincipal = new WindowsPrincipal(wi);
Class1.MyCheck();
}
}
}
}
This is the project layout in Visual Studio:
Also make sure you modify the mscorlib.fakes file that was automatically generated like this:
<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/" Diagnostic="true" TargetFrameworkVersion="v4.6">
<Assembly Name="mscorlib" />
<ShimGeneration>
<Clear />
<Add Namespace="System.Security.Principal" />
</ShimGeneration>
</Fakes>
It means I want the whole System.Security.Principal
namespace to be shimed and I suggest you use framework 4.6 for both projects and add the corresponding TargetFrameworkVersion attribute.
Now, when you run the test, this is what you'll see:
Ok, in your specific scenario, I may not be able to use fakes, but the underlying technology it relies on just reroutes all APIs (it's lower than .NET in fact, it's called Detours) I believe and allows all these hackery.
To sum up: if it runs on my machine, I can hack it (unless I don't have physical access to my machine).