Liath
Liath

Reputation: 10191

Risks of loading Assemblies via reflection

This is a followup from my previous question, I want to examine the StrongName of an assembly before loading it (either via a file on the hard disk or via the byte data). To ensure that it's been created by me.

Are there any security risks to consider when using Assembly.LoadFrom or Assembly.Load, could malicious code be executed by loading it into these variables? Should I consider loading these assemblies in an AppDomain to read them?

Here's the rest of my code:

  Assembly dll = Assembly.LoadFrom("UnauthorisedPlugin.dll");

  byte[] thisDllKey = Assembly.GetExecutingAssembly().GetName().GetPublicKey();
  byte[] dllKey = dll.GetName().GetPublicKey();
  if (Enumerable.SequenceEqual(thisDllKey, dllKey))
  {
    Type pluginType = dll.GetTypes().Single();
    IPlugin unauthPlugin = (IPlugin)Activator.CreateInstance(pluginType);

    Console.WriteLine(unauthPlugin.Run());
  }
  else
  {
    Console.WriteLine("The DLL is not authorised");
  }

  Console.ReadLine();

Upvotes: 2

Views: 686

Answers (2)

Steven
Steven

Reputation: 172865

An attacker that can write altered plugins to your plugin directory will most likely also be able to write to the application directory itself (since the safest place to store the plugin directory is inside the application directory). Since an attacker can write to that location, it can also replace your .exe with an exe that removes the security check.

In other words, checking the SNK of an assembly is not that useful.

Upvotes: 1

Lloyd
Lloyd

Reputation: 29668

You can mitigate some of this by loading the assembly in reflection only mode:

The reflection-only load context allows you to examine assemblies compiled for other platforms or for other versions of the .NET Framework. Code loaded into this context can only be examined; it cannot be executed. This means that objects cannot be created, because constructors cannot be executed.

You can do this using Assembly.ReflectionOnlyLoad() and Assembly.ReflectionOnlyLoadFrom().

See here for more information - http://msdn.microsoft.com/en-us/library/ms172331.aspx

Upvotes: 5

Related Questions