Nick Grattan's Blog

About Microsoft SharePoint, .NET, Natural Language Processing and Machine Learning

Sandboxing an Assembly

leave a comment »

If your application is loading an assembly and then executing code within that assembly you may want to “sandbox” that assembly and run the assembly in the “Internet Zone”. This will control access to local resources, such as the file system and the registry. To do this, the assembly must be loaded into an AppDomain, and this has the additional advantage that the assembly can be unloaded once execution is completed.

The following ‘using’ statements will be required for these code examples:

using System.Security;

using System.Security.Policy;

using System.Security.Permissions;

First, you need to create an evidence object which specifies the “Internet Zone”:

object[] hostEvidence = { new Zone(SecurityZone.Internet) };

Evidence intEvidence = new Evidence(hostEvidence, null);

The AppDomain can now be created and the assembly loaded into the AppDomain:

AppDomain ad = AppDomain.CreateDomain(“AddIns”, null);

 

TestLib.TestLib remoteWorker = (TestLib.TestLib)

      ad.CreateInstanceFromAndUnwrap(

               @”TestLib.dll”,

               “TestLib.TestLib”,

               false, // don’t ignore case

               0, // binding attributes

               null, // use default binder

               null, // args passed to constructor (none)

               null, // use culture from current thread  

               null, // no activation attributes

               intEvidence); //evidence

In this case the assembly is loaded from a file  called”TestLib.DLL”. By calling CreateInstanceFromAndUnwrap an instance of the class “TestLib” is created and through this instance methods in the class can be called:

double l;

l = remoteWorker.theMethod();

This assumes that the class TestLib has a method called ‘theMethod’ that takes no arguments and returns a double.

You might be tempted to apply the evidence to the AppDomain – the second parameter in CreateDomain is null in the code above but a reference to the evidence can be passed. However, when the AppDomain tries to load the assembly it will fail as the AppDomain has no access to the file system and so cannot load the assembly!

Written by Nick Grattan

July 13, 2007 at 1:53 pm

Posted in Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: